Can I run JavaScript before the whole page is loaded?
Yes, you can execute JavaScript early by using script tags in the head
with the event DOMContentLoaded
fired when the basic DOM is ready.
If you have code that doesn't require DOM elements, you can use immediate script tags at the top of body
.
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.
- 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).
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.
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.
- The jQuery approach: For those still on the jQuery train, there's
$(document).ready()
. Same effect, different syntax!
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 thehead
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 asmodule
, don't run until after the HTML is fully parsed and beforeDOMContentLoaded
.
Was this article helpful?