Explain Codes LogoExplain Codes Logo

How to defer inline Javascript?

javascript
defer-execution
script-tag
module-scripts
Alex KataevbyAlex Kataev·Nov 30, 2024
TLDR

With JavaScript, you can mimic the defer behavior for inline scripts. The quick solution is to wrap your inline JavaScript code in a function, then call that function with the event listener DOMContentLoaded which ensures your script runs only after the DOM is ready.

// Your witty function name goes here function myInlineScript() { // Yes, this is where your inline JS code lives } // Wait, don't go yet! Let the DOM prepare itself document.addEventListener('DOMContentLoaded', myInlineScript);

This method ensures your inline script will only execute once the document is fully parsed. Now, your page won't have to play catch with HTML parsing.

Optimal Script Placement

Even in the JavaScript world, location matters. To defer execution, place your <script> tags right before the closing </body> tag. This way, the browser can finish parsing DOM elements before executing away:

<body> <!-- Your beautiful markup --> <script> // Just hanging out here, waiting for DOM to be ready </script> </body>

Using Module Scripts as an Alternative

Modules are like the Swiss Army knife of JavaScript. With type="module" in your script tags, scruffy inline scripts get a makeover and gain defer superpowers:

<script type="module"> // No worries, I'm a module. I'll wait my turn </script>

Wait! Don't run yet

For those who love a good game plan, chain events or use promises to strategize your inline script execution. Set event listeners to ensure your dependencies load before your inline script and avoid the Javascript equivalent of a "mic drop".

Base64 URLs for Inline Script Embedding

Channel your inner James Bond by using a Base64 URL in a module script:

<script type="module" src="data:text/javascript;base64,/* Your inline script, shaken not stirred */"></script>

Design Patterns with Template Engines

Libraries like Handlebars or Angular provide automated pattern designs to structure scripts for deferment. It's like getting a GPS for your inline scripts.

Testing Inline Script Execution

A good developer is like a crafty detective. Monitor the network activities in your browser's developer tools or plant console.log bread crumbs in your code for testing:

document.addEventListener('DOMContentLoaded', () => { console.log("Captain, the DOM is ready!"); });