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?
This code works well.
But
window.onload
method has various dependencies. So it may not work all the time.You can put a "onload" attribute inside the body
Or if you are using jQuery, you can do
I hope it answer your question.
Note that the $(window).load will execute after the document is rendered on your page.
$(window).on("load", function(){ ... });
.ready() works best for me.
.load() will work, but it won't wait till the page is loaded.
Doesn't work for me, breaks the next-to inline script. I am also using jQuery 3.2.1 along with some other jQuery forks.
To hide my websites loading overlay, I use the following:
I find sometimes on more complex pages that not all the elements have loaded by the time window.onload is fired. If that's the case, add setTimeout before your function to delay is a moment. It's not elegant but it's a simple hack that renders well.
becomes...
Working Fiddle
If the scripts are loaded within the
<head>
of the document, then it's possible use thedefer
attribute in script tag.Example:
From https://developer.mozilla.org: