Running javascript code on page load, without using the onload tag

前端 未结 5 1213
傲寒
傲寒 2020-12-18 10:33

How can I run a JavaScript code when the page loads without using the onload tag?

I\'m trying to run this script:



        
5条回答
  •  爱一瞬间的悲伤
    2020-12-18 11:15

    Like this:

    window.onload = function WindowLoad(event) {
        alert("Page is loaded");
    }
    

    Edit: if some other code is also using window.onload after that script then it will be "overwritten" - to make sure it's executed (and abort any other onload) put it in the bottom of the page.

    Edit 2: On second thought, you better add onload listener instead of overwriting it:

    
    

    This will prevent any conflicts with existing code and is more cross browser as far as I can tell.

    Live test case is available here: http://jsfiddle.net/yahavbr/GZPTG/ tested for IE8, Chrome and Firefox (latest versions) feel free to test for more.

提交回复
热议问题