$( document ).ready()&$(window).load()

 

$( document ).ready()

https://learn.jquery.com/using-jquery-core/document-ready/javascript

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.html

 

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>$( document ).ready()</title>
    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        $(document).ready(function () {
            alert("document loaded");
        });
    //document ready 簡寫
    $(function() {
        // ...代碼...
    })
$(window).load(function () { alert("window loaded"); }); </script> </head> <body> <iframe src="http://techcrunch.com"></iframe> </body> </html>

 

Experienced developers sometimes use the shorthand $() for $( document ).ready(). If you are writing code that people who aren't experienced with jQuery may see, it's best to use the long form.java

1
2
3
4
// Shorthand for $( document ).ready()
$(function() {
console.log( "ready!" );
});

You can also pass a named function to $( document ).ready() instead of passing an anonymous function.jquery

1
2
3
4
5
6
7
8
9
// Passing a named function instead of an anonymous function.
 
function readyFn( jQuery ) {
// Code to run when the document is ready.
}
 
$( document ).ready( readyFn );
// or:
$( window ).load( readyFn );

 

DOMContentLoaded

https://developer.mozilla.org/zh-CN/docs/DOM/DOM_event_reference/DOMContentLoaded瀏覽器

當頁面中的文檔樹解析完成時,在頁面的Document對象上,會觸發DOMContentLoaded事件.該事件表明了,頁面的DOM樹已經構建完成,但頁面引用的樣式表和圖像文件,以及包含的框架頁面可能尚未加載完成,在頁面徹底加載完成時,會觸發另一個相似的稱爲"load"的事件.框架

該事件會冒泡到當前頁面的window對象上.但框架頁面中文檔加載完成時並不會觸發父頁面的DOMContentLoaded事件.ide

瀏覽器兼容性

 

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 0.2 1.0 (1.7 or earlier) 9.0 9.0 3.1
<script>
  document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOM fully loaded and parsed");
  });
</script>
相關文章
相關標籤/搜索