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

前端 未结 5 1215
傲寒
傲寒 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:13

    You can do

    
    
    
    

    A cleaner way would be

    
    
    
    

    since this allows for multiple eventhandlers to the same event

    A better way is usually to react to domReady though.

    Most javascript libraries support easy ways to hook into domReady. In jQuery for example you can do it like this:

    $(function() {
    /* code here will be run as soon as the dom is ready to be interacted with, 
       but before document.load occurs which means you don't have to wait for 
       images to load for example
    */
    });
    

提交回复
热议问题