<!doctype html> <html> <head> </head> <body> Your HTML here
<script> // self executing function here (function() { // your page initialization code here // the DOM will be available here
})(); </script> </body> </html>
HTML
2. 现代浏览器的实现
对于IE9及以上版本以及Chrome、Firefox、Safari的任何版本,可以使用以下方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functiondocReady(fn) { // see if DOM is already available if (document.readyState === "complete" || document.readyState === "interactive") { // call on next available tick setTimeout(fn, 1); } else { document.addEventListener("DOMContentLoaded", fn); } }
// Usage docReady(function() { // DOM is loaded and ready for manipulation here });
baseObj[funcName] = function(callback, context) { if (typeof callback !== "function") { thrownewTypeError("callback for docReady(fn) must be a function"); } if (readyFired) { setTimeout(function() {callback(context);}, 1); return; } else { readyList.push({fn: callback, ctx: context}); } if (document.readyState === "complete") { setTimeout(ready, 1); } elseif (!readyEventHandlersInstalled) { if (document.addEventListener) { document.addEventListener("DOMContentLoaded", ready, false); window.addEventListener("load", ready, false); } else { document.attachEvent("onreadystatechange", readyStateChange); window.attachEvent("onload", ready); } readyEventHandlersInstalled = true; } } })("docReady", window);
// Usage // pass a function reference docReady(fn);
// use an anonymous function docReady(function() { // code here });
// pass a function reference and a context // the context will be passed to the function as the first argument docReady(fn, context);
// use an anonymous function with a context docReady(function(context) { // code here that can use the context argument that was passed to docReady }, ctx);
JAVASCRIPT
4. 其他实现方式
使用document.addEventListener(IE9及以上):
1 2 3
document.addEventListener("DOMContentLoaded", function(event) { // Your code to run since DOM is loaded and ready });
JAVASCRIPT
跨浏览器兼容的技巧:
1 2 3 4 5
functionr(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()} // use like r(function(){ alert('DOM Ready!'); });
JAVASCRIPT
检查document.readyState:
1 2 3 4 5 6 7 8
document.onreadystatechange = function () { var state = document.readyState; if (state == 'interactive') { init(); } elseif (state == 'complete') { initOnCompleteLoad(); } };