document.ready 與 onload 的區別

摘要

document.ready 是指文檔加載好, dom 加載好,僅包含在它以前的 script 、css 標籤 , 但不包含 img 標籤是否加載完成, 由於頁面是按順序執行的。javascript

onload 是指頁面徹底加載好,包括全部節點,甚至 img 標籤css

固然咱們編碼通常都是把基礎庫放在head 頭部,保證最早加載,業務代碼放在最後,避免出現庫未加載完成的狀況。html

固然如今前端工程通常使用 webpack 等打包技術,在編譯打包過程當中就徹底實現了依賴項前置的功能。前端

測試

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>

<body onload="onload()">
    <img src="http://upload.chinaz.com/upimg/allimg/110630/0901070.jpg" />
    <script type="text/javascript" src="http://libs.cdnjs.net/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            console.log('document ready');
        });
    </script>
    <script type="text/javascript">
        console.log('haha');
    </script>
</body>

<script type="text/javascript">
function onload() {
    console.log('onload');
}
</script>
</html>
// 打印   
//haha
//document ready     
//onload
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>

<body onload="onload()">
    <img src="http://upload.chinaz.com/upimg/allimg/110630/0901070.jpg" />
    <script type="text/javascript">
        $(document).ready(function() {
            console.log('document ready');
        });
    </script>
    <script type="text/javascript">
        console.log('haha');
    </script>
    <script type="text/javascript" src="http://libs.cdnjs.net/jquery/3.2.1/jquery.min.js"></script>
</body>

<script type="text/javascript">
function onload() {
    console.log('onload');
}
</script>
</html>
//打印  
//$ undefined    
//haha   
//onload
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>

<body onload="onload()">
    <img src="http://upload.chinaz.com/upimg/allimg/110630/0901070.jpg" />

    <script type="text/javascript">
        console.log('haha');
    </script>
    <script type="text/javascript">
        $(document).ready(function() {
            console.log('document ready');
        });
    </script>
    <script type="text/javascript" src="http://libs.cdnjs.net/jquery/3.2.1/jquery.min.js"></script>

</body>

<script type="text/javascript">
function onload() {
    console.log('onload');
}
</script>
</html>
//打印  
//haha   
//$ undefined    
//onload
相關文章
相關標籤/搜索