JQuery's ready function is different from JS's onload

  • 2020-03-29 23:56:07
  • OfStack

The difference between JQuery's ready function and JS's onload:
1. Execution time
Window.onload must wait until all the elements in the page, including the image, have been loaded.
$(document).ready() is executed after the DOM structure has been drawn and does not have to wait until it has been loaded.


2. Write different Numbers
Window.onload cannot be written more than one at a time; if there are more than one window.onload method, only one will be executed
$(document).ready() can be written more than one at a time, and both can be executed


3. Simplify
Window.onload doesn't simplify
The $(document). Ready (function () {}) can be abbreviated as $(function () {});

Example:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>ready and js In the onload The difference between </title>
        <script type="text/javascript" src="jquery-core/jquery-1.8.0.js"></script>

        <script type="text/javascript">

            //The onload property of the window object in js executes the jsFunction1 function
            window.onload=jsFunction1;

            //The onload property of the window object in js executes the jsFunction2 function
            window.onload=jsFunction2;

            //The ready method of jquery executes the jqFunction1 function
        $(document).ready(jqFunction1);

        //The ready method of jquery executes the jqFunction2 function
        $(document).ready(jqFunction2);

        //JsFunction1 function
        function jsFunction1(){
                alert("jsFunction1");         
        }

        //JsFunction2 function
        function jsFunction2(){
        alert("jsFunction2");
        }

        //JqFunction1 function
        function jqFunction1(){
           alert("jqFunction1");
        }

        //JqFunction2 function
        function jqFunction2(){
        alert("jqFunction2");
        }
        </script>

    </head>
    <body>
        <h1>ready and js In the onload The difference between </h1>
    </body>
</html>


Related articles: