DEV Community

Cover image for How to use jQuery with Astro
Salma Alam-Naylor
Salma Alam-Naylor

Posted on • Updated on • Originally published at

How to use jQuery with Astro

Since it’s alpha release in 2021, Astro is an open source web framework that has been growing steadily in popularity. One of the unique selling points of Astro is that you can “bring your own UI library”, giving you the ability to use React, Preact, Vue, SolidJS, Svelte and more — all within a single Astro project — or even a single file!

However, jQuery is still the most popular and most used JavaScript library on the web. And it was my first taste of writing JavaScript for the browser back in 2014 (yes, before I learned plain JavaScript syntax, don’t hate).

And without a jQuery integration for Astro guide available (yet), I wanted to see if I could use jQuery in an Astro project. “Why, Salma, why?” I hear you cry. Well, why not? Even Astro co-creator Matthew Phillips loves jQuery.

Use the is:inline template directive

By default, Astro processes, optimises and bundles any <script> tags that it finds in a layout, page or component file. Initially, I tried installing the jQuery package via npm, and importing it inside a script tag. But given the import was bundled up by Astro, the good old jQuery $ wasn’t able to initialise and get access to the window object and DOM. I also found a highly experiment jQuery integration for Astro that… just didn’t work at all 🙃.

You might be familiar with adding jQuery to an HTML file using a <script> tag referencing the minified source code from the jQuery CDN or a local file. We can achieve this in Astro by preventing the bundling of the jQuery import by adding the is:inline directive to <script> tags in layout, page or component files. This is also really useful to know if you want to interact with elements on the page using plain JavaScript even without jQuery.

To use jQuery in an Astro project, you can choose to reference the minified source code from the CDN, or download the source code to the public folder of your project, and reference it from there.

<script is:inline src=""></script>
Enter fullscreen mode Exit fullscreen mode

Using jQuery in Astro components and pages

If you choose to import jQuery to a layout file, you’re free to use jQuery syntax in your page and component files using a <script> tag with the is:inline directive — or let Astro bundle and optimise the code by omitting the directive. Like so:

<script is:inline>
  $("button").on("click", () => {console.log("Button clicked!")});

<!-- or if you want the code bundled and optimised -->

  $("button").on("click", () => {console.log("Button clicked!")});
Enter fullscreen mode Exit fullscreen mode

jQuery is great!

That’s it. That’s the headline. Read more about the is:inline directive on the official Astro documentation.

Top comments (0)