How to make JavaScript execute after page load?
Use DOMContentLoaded
to run JavaScript as soon as the HTML document has been fully parsed:
For scenarios requiring all resources such as images to load, use load
:
To set scripts to execute after the HTML is fully parsed not blocking the HTML parsing process, use the defer
attribute:
Place deferred scripts in the <head>
section to support a clear separation of HTML and JavaScript.
Deciding between defer, async, or inline scripts
Discover when to use defer
, async
, or inline scripts to power-up your site loading speed.
defer
attribute
Choose defer
for scripts that can wait their turn, executing them after the document is parsed but before firing DOMContentLoaded
.
- Executes scripts in order like a polite British queue.
- Only affects scripts with an external source (i.e., the
src
attribute).
async
attribute
Use async
for scripts that can't wait and need to load as the rest of the page continues parsing.
- Executes scripts ASAP as they load, relying on their initiative in a 'Bourne Identity' style, order not guaranteed.
- Great for lone-wolf scripts that don't rely on others.
Inline scripts
Inline <script>
tags placed right before the </body>
tag execute after the HTML is parsed but does not assure all resources are loaded. They're the can-do spirit of scripts.
Deploying jQuery and ensuring cross-browser support
Deploy the power of jQuery for projects already using it when the DOM is fully at your disposal or the page is fully loaded:
For cross-browser support like a super-secret-agent spy, use addEventListener
with a fallback:
Advanced techniques for complex loading situations
Sometimes single events are not enough; for these, use these complex-loading survival skills.
Handling multiple onload handlers
For multiple functions that need the post-page load stage, organize them into a solitary onload
handler:
Using document readiness for unique loading behavior
Customize your loading behavior by checking document.readyState
:
Tackling dynamically injected scripts
For scripts dynamically injected into the page (added via JavaScript), ensure they mimic defer
behavior:
Was this article helpful?