\n\n\nIf you have code that doesn't require DOM elements, you can use immediate script tags at the top of body.\n\nhtml\n\n\n\nCritical: Manipulating DOM might fail if the elements are not loaded yet. Employ JavaScript for non-DOM tasks or to set up callbacks / listeners for later.","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Alex Kataev","url":"https://explain.codes//author/alex-kataev"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2024-10-31T23:15:01.505Z","dateModified":"2024-10-31T23:15:02.936Z"}
Explain Codes LogoExplain Codes Logo

Can I run JavaScript before the whole page is loaded?

javascript
async
defer
javascript-modules
Alex KataevbyAlex Kataev·Oct 31, 2024
TLDR

Yes, you can execute JavaScript early by using script tags in the head with the event DOMContentLoaded fired when the basic DOM is ready.

<script> document.addEventListener('DOMContentLoaded', () => { // When you need to ensure the DOM is loaded console.log('DOM ready, unleash the JS!'); }); </script>

If you have code that doesn't require DOM elements, you can use immediate script tags at the top of body.

<script> // Code that can chill without DOM console.log('Who needs DOM? I can run anyway.'); </script>

Critical: Manipulating DOM might fail if the elements are not loaded yet. Employ JavaScript for non-DOM tasks or to set up callbacks / listeners for later.

Leveraging defer and async

Optimize your JavaScript loading using async and defer. These attributes control the fetching and execution behavior of your scripts.

  • Defer: With the defer attribute, browser fetches the script during HTML parsing but delays execution until HTML parsing has finished.
<script defer src="myScript.js"></script>
  • Async: The async attribute allows the browser to continue parsing the HTML while the script is being fetched. As soon as it's ready, script execution takes place (which may be during HTML parsing).
<script async src="myScript.js"></script>

JavaScript modules

Another powerful mechanism: JavaScript modules. By using type="module" in your script tags, you can have the script run after HTML parsing, but before the page's resources have finished loading.

<script type="module" src="myModule.js"></script>

Handling the DOM

To ensure safe DOM manipulation, remember the HTML has to be fully loaded. Different approaches include:

  • DOMContentLoaded event: Triggers when the initial HTML document is completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
<script> document.addEventListener('DOMContentLoaded', () => { // DOM's ready, go manipulate those elements! console.log('The DOM is now my playground!'); }); </script>
  • The jQuery approach: For those still on the jQuery train, there's $(document).ready(). Same effect, different syntax!
<script> $(document).ready(() => { // After DOM's loaded, it's ready for some good 'ol jQuery action! console.log('Is jQuery still a thing? Anyway, let's do this!'); }); </script>

Advanced strategies

Consider these high-level strategies for optimal script placement and performance:

Prefetching and preloading

Modern browsers achieve faster script execution by prefetching and preloading scripts:

  • Prefetch: Specific to script tags placed near the end of your document, these scripts are fetched early in the page load lifecycle to minimize execution delays.
  • Preload: Use <link rel="preload"> within the head tag to specify high-priority resources to be loaded before others.

Order and timing of execution

Understanding the order and timing of script execution can prove helpful in optimizing script placement:

  • Scripts with the async attribute run as soon as they can, possibly during HTML parsing.
  • Scripts with the defer attribute, or those typed as module, don't run until after the HTML is fully parsed and before DOMContentLoaded.