How to run a function when the page is loaded?

前端 未结 9 1625
小鲜肉
小鲜肉 2020-11-22 11:02

I want to run a function when the page is loaded, but I don’t want to use it in the tag.

I have a script that runs if I initialise it in th

9条回答
  •  不要未来只要你来
    2020-11-22 12:05

    window.onload = function() { ... etc. is not a great answer.

    This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours. So, you can spend lots of hours later trying to figure out why something that was working isn't anymore.

    A more robust answer here:

    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;
        }
    }
    

    Some code I have been using, I forget where I found it to give the author credit.

    function my_function() {
        // whatever code I want to run after page load
    }
    if (window.attachEvent) {window.attachEvent('onload', my_function);}
    else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
    else {document.addEventListener('load', my_function, false);}
    

    Hope this helps :)

提交回复
热议问题