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?
Use this code with jQuery library, this would work perfectly fine.
Keep in mind that loading the page has more than one stage. Btw, this is pure JavaScript
"DOMContentLoaded"
This event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, 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.
Exectues after DOM is loaded (before img and css):
"load"
A very different event, load, should only be used to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
Exectues after everything is loaded and parsed:
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
My advise use
asnyc
attribute for script tag thats help you to load the external scripts after page loadJust define
<body onload="aFunction()">
that will be called after the page has been loaded. Your code in the script is than enclosed byaFunction() { }
.Look at hooking
document.onload
or in jQuery$(document).load(...)
.