Moving our search drop down from Algolia to Alpine.js

Published under JavaScript.

So for the search drop down you see on this website, I initially went with Algolia's InstantSearch.js. This was my implementation:

So this isn't too bad, easy enough to understand and manage. However, my production bundle was 227kb (this includes highlight.js, which I am using for code syntax highlighting).

Seeing this, I decided to try out Alpine.js by Caleb Porzio to see if I could reduce my bundle size without sacrificing functionality. Here's the Alpine.js implementation:

A couple things to note:

  • I'm manually calling the Algolia search API.

  • I'm using fetch (without the polyfill) to make the search request.

  • Since there's currently no x-for/loop syntax in Alpine.js, when I receive the search results I join together a string of HTML and then insert that into the DOM. This isn't 100% safe, but I'm the only one in control of the content, so I'm okay with it for now. I wouldn't recommend doing this for scenarios where you do not control the content.

And to top it off, the production build JS is down to 27kb: /js/app.js 27.5 kB

If you want to try a demo of the search component, feel free to check out the search component on this website!


Thanks for reading!

Did you find this post useful? Let me know on Twitter! If you found an issue with the content, submit a pull request!

Subscribe to my newsletter to know when I publish more content in the future.

❤️ Likes: 0
📣 Retweets: 0
💬 Replies: 0
🙊 Mentions: 0