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 01:45

Use this code with jQuery library, this would work perfectly fine.

$(window).bind("load", function() { 

  // your javascript event

});
查看更多
浅入江南
3楼-- · 2018-12-31 01:47

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):

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 stylesheets

"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:

window.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

查看更多
姐姐魅力值爆表
4楼-- · 2018-12-31 01:47

My advise use asnyc attribute for script tag thats help you to load the external scripts after page load

<script type="text/javascript" src="a.js" async></script>
<script type="text/javascript" src="b.js" async></script>
查看更多
孤独寂梦人
5楼-- · 2018-12-31 01:48

<script type="text/javascript">
$(window).bind("load", function() { 

// your javascript event here

});
</script>

查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 01:50

Just define <body onload="aFunction()"> that will be called after the page has been loaded. Your code in the script is than enclosed by aFunction() { }.

查看更多
永恒的永恒
7楼-- · 2018-12-31 01:54

Look at hooking document.onload or in jQuery $(document).load(...).

查看更多
登录 后发表回答