JavaScript that executes after page load

2018-12-31 01:32发布

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?

22条回答
初与友歌
2楼-- · 2018-12-31 02:05
<body onload="myFunction()">

This code works well.

But window.onload method has various dependencies. So it may not work all the time.

查看更多
不再属于我。
3楼-- · 2018-12-31 02:06

You can put a "onload" attribute inside the body

...<body onload="myFunction()">...

Or if you are using jQuery, you can do

$(document).ready(function(){ /*code here*/ }) 

or 

$(window).load(function(){ /*code here*/ })

I hope it answer your question.

Note that the $(window).load will execute after the document is rendered on your page.

查看更多
墨雨无痕
4楼-- · 2018-12-31 02:06

$(window).on("load", function(){ ... });

.ready() works best for me.

$(document).ready(function(){ ... });

.load() will work, but it won't wait till the page is loaded.

jQuery(window).load(function () { ... });

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:

<script>
$(window).on("load", function(){
$('.loading-page').delay(3000).fadeOut(250);
});
</script>
查看更多
怪性笑人.
5楼-- · 2018-12-31 02:07

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.

window.onload = function(){ doSomethingCool(); };

becomes...

window.onload = function(){ setTimeout( function(){ doSomethingCool(); }, 1000); };
查看更多
旧人旧事旧时光
6楼-- · 2018-12-31 02:08

Working Fiddle

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
   alert("Page is loaded");
}
</script>
</head>

<body onload="myFunction()">
<h1>Hello World!</h1>
</body>    
</html>
查看更多
冷夜・残月
7楼-- · 2018-12-31 02:10

If the scripts are loaded within the <head> of the document, then it's possible use the defer attribute in script tag.

Example:

<script src="demo_defer.js" defer></script>

From https://developer.mozilla.org:

defer

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.

This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.

To achieve a similar effect for dynamically inserted scripts use async=false instead. Scripts with the defer attribute will execute in the order in which they appear in the document.

查看更多
登录 后发表回答