#script tag does not work in 404.astro

4 messages · Page 1 of 1 (latest)

sick scaffold
#

if I put a script tag in my 404.astro file, the javascript does not get executed when the 404 page is displayed. How do I fix this?

stray sphinxBOT
#

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

#

Astro processes <script> tags in .astro files by default. However, there are certain situations where Astro will not process your script tags. For instance, adding type="module" or any attribute other than src to a <script> tag will cause Astro to treat the tag as if it had an is:inline directive. The same will be true when the script is written in a JSX expression.

To prevent Astro from processing a script, you can add the is:inline directive. This will render the script into the HTML exactly as written. Here's an example:

<script is:inline>  
// Your JavaScript code here
// Will be rendered into the HTML exactly as written!  
// Local imports are not resolved and will not work.  
// If in a component, repeats each time the component is used.
</script>

If you want to include JavaScript files in your 404 page, you can do so by referencing these in a <script> tag’s src attribute. If your JavaScript file lives inside of public/ or on a CDN, you should include the is:inline directive. This approach skips the JavaScript processing, bundling, and optimizations that are provided by Astro when you import scripts. Here's an example:

<!-- absolute path to a script at `public/my-script.js` -->
<script is:inline src="/my-script.js"></script>
<!-- full URL to a script on a remote server -->
<script is:inline src="<https://my-analytics.com/script.js"></script>>

If you're still having trouble, it might be due to your site's Content Security Policy (CSP) disallowing running inline <script> tags, which Astro outputs by default. You can update your CSP to include script-src: 'unsafe-inline' to allow inline scripts to run. Alternatively, you can use a third-party integration such as astro-shield to generate the CSP headers for you.