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

As Daniel says, you could use document.onload.

The various javascript frameworks hwoever (jQuery, Mootools, etc.) use a custom event 'domready', which I guess must be more effective. If you're developing with javascript, I'd highly recommend exploiting a framework, they massively increase your productivity.

查看更多
浅入江南
3楼-- · 2018-12-31 01:58

If you are using jQuery,

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

is equivalent to

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

See What event does JQuery $function() fire on?

查看更多
何处买醉
4楼-- · 2018-12-31 01:59
document.onreadystatechange = function(){
     if(document.readyState === 'complete'){
         /*code here*/
     }
}

look here: http://msdn.microsoft.com/en-us/library/ie/ms536957(v=vs.85).aspx

查看更多
闭嘴吧你
5楼-- · 2018-12-31 01:59

use self execution onload function

window.onload = function (){
    /* statements */
}();   
查看更多
初与友歌
6楼-- · 2018-12-31 02:04

These solutions will work:

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

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

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;
    }
}
查看更多
登录 后发表回答