Several methods for the page to automatically execute (load) js

1. JS method
1. The easiest way to call is to write it directly into the body tag of html:

<html>
    <body onload="load();">
    </body>
</html>

 2. Call in the JS statement:

<script type="text/javascript">
    function myfun()   {    
        alert("this window.onload");   
    }   
    /* call myfun() with window.onload */ 
     
    // no parentheses
    window.onload = myfun;
</script>

 3. Js calls the onload method 

<script type="text/javascript">
    window.onload = function(){
        func1();
        func2();
        func3();
    }
</script>

 2. JQ method

 

1. Execute after all documents on the entire page are loaded. Unfortunately this approach requires not only the DOM tree of the page to be fully loaded, but also all external images and resources to be fully loaded. Even more unfortunately, if external resources, such as images, take a long time to load, then this js method will feel slower to execute. In other words, this is the most rigorous method of executing the method after the page is loaded.

window.onload =function() {
    $("table tr:nth-child(even)").addClass("even");
    //this is jquery code
};

 2. Just load all the DOM structure and execute the method before the browser puts all the HTML into the DOM tree. Include before loading external images and resources.

$(document).ready(function() {
    //Any js effects that need to be executed
    $("table tr:nth-child(even)").addClass("even");
});

 There is a very simple way of writing:

$(function() {
    $( " table tr:nth-child(even) " ).addClass( " even " ); 
     // Any js effects that need to be executed 
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326010653&siteId=291194637