I'm executing an external script, using a <script>
inside <head>
.
Now since the script executes before the page has loaded, I can't access the <body>
, among other things. I'd like to execute some JavaScript after the document has been "loaded" (HTML fully downloaded and in-RAM). Are there any events that I can hook onto when my script executes, that will get triggered on page load?
If you are using an <script> inside <head> then use the onload attribute inside the <body> tag to Execute JavaScript after page load. It will run the function as soon as the webpage has been loaded.
Many JavaScript-enhanced web pages have scripts that must be executed automatically when the page is loaded. A web page containing a "scrolling status bar message," for example, should be able to start scrolling the message immediately after the page has loaded, without user interaction.
The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded.
These solutions will work:
As mentioned in comments use defer:
<script src="deferMe.js" defer></script>
or
<body onload="script();">
or
document.onload = function ...
or even
window.onload = function ...
Note that the last option is a better way to go since it is unobstrusive and is considered more standard.
<script src="script.js" defer></script>
Using defer will trigger after domInteractive (document.readyState = "interactive") and just before "DOMContentLoaded" Event is triggered. If you need to execute the script after all resources (images, scripts) are loaded use "load" event or target one of the document.readyState states. Read further down for more information about those events / states, as well as async and defer attributes corresponding to script fetching and execution timing.
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.
Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating.
Resource: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attributes
* See the images at the bottom for feather explanation.
This event is fired when the initial HTML document has been completely loaded and parsed, without waiting for style sheets, images, and subframes to finish loading. At this stage you could programmatically optimize loading of images and CSS based on user device or bandwidth speed.
Executes after DOM is loaded (before images and CSS):
document.addEventListener("DOMContentLoaded", function(){
//....
});
Note: Synchronous JavaScript pauses parsing of the DOM. If you want the DOM to get parsed as fast as possible after the user requested the page, you could turn your JavaScript asynchronous and optimize loading of style sheets
Executes after everything is loaded and parsed:
document.addEventListener("load", function(){
// ....
});
MDN Resources: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded https://developer.mozilla.org/en-US/docs/Web/Events/load
MDN list of all events:
https://developer.mozilla.org/en-US/docs/Web/Events
// Place in header (do not use async or defer)
document.addEventListener('readystatechange', event => {
switch (document.readyState) {
case "loading":
console.log("document.readyState: ", document.readyState,
`- The document is still loading.`
);
break;
case "interactive":
console.log("document.readyState: ", document.readyState,
`- The document has finished loading DOM. `,
`- "DOMContentLoaded" event`
);
break;
case "complete":
console.log("document.readyState: ", document.readyState,
`- The page DOM with Sub-resources are now fully loaded. `,
`- "load" event`
);
break;
}
});
MDN Resources: https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
If your script uses async or defer read this: https://flaviocopes.com/javascript-async-defer/
Reasonably portable, non-framework way of having your script set a function to run at load time:
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
yourFunctionName(evt);
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With