#Use external js in Astro

1 messages · Page 1 of 1 (latest)

mystic sequoia
#

I have doubt regarding Astro. How to use external js file in '/public' folder with Astro component?

native pilotBOT
#

Hi @mystic sequoia. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can use an external JavaScript file located in the public/ directory of your Astro project in a couple of ways:

  1. Absolute URL Path: If your JavaScript file is in the public/ directory, you can reference it by an absolute URL path directly in your Astro component templates. For example, you can use a <script> tag with the src attribute pointing to the file's location. This approach skips the JavaScript processing, bundling, and optimizations provided by Astro. This method is preferred for any external scripts that have already been published and minified separately from Astro.
<script src="/some-external-script.js"></script>

Source (https://docs.astro.build/en/guides/upgrade-to/v1/)

  1. Using is:inline directive: To load scripts outside of your project’s src/ folder, include the is:inline directive. This approach also skips the JavaScript processing, bundling, and optimizations that are provided by Astro.
<script is:inline src="/my-script.js"></script>

Source (https://docs.astro.build/en/guides/client-side-scripts/)

Remember, files in the public/ directory are not built or bundled by Astro, which means they are copied directly into your final build untouched. You can place JavaScript in your public/ directory, but be aware that those files will not be bundled or optimized in your final build. Source (https://docs.astro.build/en/core-concepts/project-structure/)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: