documnet.onload與$(document).ready等執行順序測試

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .circle{
            width: 0;
            height: 0;
            border: 20px solid;
            border-radius: 5px;
        }
    </style>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        // function f(id) {
        //     return new Promise(function (resolve,reject) {
        //         setTimeout((function (id) {
        //             return function () {
        //                 console.log("Promise"+id);
        //                 resolve(id);
        //             }
        //         })(id),1000)
        //     })
        // }
        //
        // var arr=[1,2,3,4];
        //
        // Promise.all(arr.map(value => f(value)))
        // .then(function (id) {
        //     console.log(id)
        //     console.log("resloved:"+id);
        // },function (id) {
        //     console.log("reject:"+id);
        // })


        // function currying(fn, ...rest1) {
        //     return function(...rest2) {
        //         return fn.apply(this, rest1.concat(rest2))
        //     }
        // }
        //
        // function sayHello(name, age, fruit) {
        //     this.a='sb';
        //     console.log(`我叫 ${name},我 ${age} 歲了, 我喜歡喫 ${fruit}`);
        // }
        //
        // const curryingShowMsg1 = currying(sayHello, '小明');
        //
        // var func = new curryingShowMsg1('16','紅燒肉');
        // console.log(func === sayHello.prototype);
        // console.log(document.getElementById("myframe").contentWindow.document);
        console.log(document.getElementById("test"))
        $(function () {
            console.log(1)
        })
        window.onload=function () {
            console.log(2)
        }
        window.onload=function () {
            console.log(3)
        }
        $(function () {
            console.log(4)
        })
        $(document).ready(function () {
            console.log(5)
        })
        $(function () {
            console.log(6);
            console.log(window.getComputedStyle(document.getElementById("test")).backgroundColor);
        })
        document.onreadystatechange=function () {
            if(document.readyState=='complete'){
                console.log(7)
            }
        }
        $(function () {
            console.log(8)
        })
    </script>
    <link rel="stylesheet" href="./css/test.css">
</head>
<body>
<div class="circle" id="SomeElementYouWantToAnimate"></div>
<div id="test"></div>
</body>
</html>

輸出結果:
在這裏插入圖片描述

結論:jquery的$(function(){})與$(document).ready(function(){})是完全相同的,且可以多次定義,按執行順序依此執行,onload只能執行依此,且執行函數爲最後一次賦值的函數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章