在没有为您完成所有跨浏览器兼容性的框架的情况下,最简单的做法就是在正文末尾调用您的代码。这比执行起来更快onload
处理程序,因为它只等待 DOM 准备就绪,而不是加载所有图像。而且,这适用于每个浏览器。
<!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>
对于现代浏览器(IE9 及更高版本的任何浏览器以及 Chrome、Firefox 或 Safari 的任何版本),如果您希望能够实现像$(document).ready()
您可以从任何地方调用的方法(无需担心调用脚本的位置),您可以使用如下所示的方法:
function docReady(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
});
如果您需要完整的跨浏览器兼容性(包括旧版本的 IE)并且不想等待window.onload
,那么你可能应该去看看像 jQuery 这样的框架是如何实现它的$(document).ready()
方法。它相当复杂,具体取决于浏览器的功能。
让您稍微了解一下 jQuery 的作用(无论脚本标签放置在何处,它都会起作用)。
如果支持,它会尝试标准:
document.addEventListener('DOMContentLoaded', fn, false);
后备至:
window.addEventListener('load', fn, false )
或者对于旧版本的 IE,它使用:
document.attachEvent("onreadystatechange", fn);
后备至:
window.attachEvent("onload", fn);
而且,IE 代码路径中有一些我不太遵循的解决方法,但看起来它与框架有关。
这是 jQuery 的完整替代品.ready()
用纯 JavaScript 编写:
(function(funcName, baseObj) {
// The public function name defaults to window.docReady
// but you can pass in your own object and own function name and those will be used
// if you want to put them in a different namespace
funcName = funcName || "docReady";
baseObj = baseObj || window;
var readyList = [];
var readyFired = false;
var readyEventHandlersInstalled = false;
// call this when the document is ready
// this function protects itself against being called more than once
function ready() {
if (!readyFired) {
// this must be set to true before we start calling callbacks
readyFired = true;
for (var i = 0; i < readyList.length; i++) {
// if a callback here happens to add new ready handlers,
// the docReady() function will see that it already fired
// and will schedule the callback to run right after
// this event loop finishes so all handlers will still execute
// in order and no new ones will be added to the readyList
// while we are processing the list
readyList[i].fn.call(window, readyList[i].ctx);
}
// allow any closures held by these functions to free
readyList = [];
}
}
function readyStateChange() {
if ( document.readyState === "complete" ) {
ready();
}
}
// This is the one public interface
// docReady(fn, context);
// the context argument is optional - if present, it will be passed
// as an argument to the callback
baseObj[funcName] = function(callback, context) {
if (typeof callback !== "function") {
throw new TypeError("callback for docReady(fn) must be a function");
}
// if ready has already fired, then just schedule the callback
// to fire asynchronously, but right away
if (readyFired) {
setTimeout(function() {callback(context);}, 1);
return;
} else {
// add the function and context to the list
readyList.push({fn: callback, ctx: context});
}
// if document already ready to go, schedule the ready function to run
if (document.readyState === "complete") {
setTimeout(ready, 1);
} else if (!readyEventHandlersInstalled) {
// otherwise if we don't have event handlers installed, install them
if (document.addEventListener) {
// first choice is DOMContentLoaded event
document.addEventListener("DOMContentLoaded", ready, false);
// backup is window load event
window.addEventListener("load", ready, false);
} else {
// must be IE
document.attachEvent("onreadystatechange", readyStateChange);
window.attachEvent("onload", ready);
}
readyEventHandlersInstalled = true;
}
}
})("docReady", window);
最新版本的代码已在 GitHub 上公开共享:https://github.com/jfriend00/docReady
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);
这已经在以下位置进行了测试:
IE6 and up
Firefox 3.6 and up
Chrome 14 and up
Safari 5.1 and up
Opera 11.6 and up
Multiple iOS devices
Multiple Android devices
工作实施和测试床:http://jsfiddle.net/jfriend00/YfD3C/
以下是其工作原理的摘要:
- 创建一个IIFE(立即调用函数表达式)因此我们可以拥有非公共状态变量。
- 声明一个公共函数
docReady(fn, context)
- When
docReady(fn, context)
被调用时,检查就绪处理程序是否已经触发。如果是这样,只需安排新添加的回调在该 JS 线程结束后立即触发setTimeout(fn, 1)
.
- 如果就绪处理程序尚未触发,则将此新回调添加到稍后调用的回调列表中。
- 检查文档是否已经准备好。如果是这样,则执行所有准备好的处理程序。
- 如果我们尚未安装事件侦听器来了解文档何时准备就绪,请立即安装它们。
- If
document.addEventListener
存在,然后使用安装事件处理程序.addEventListener()
对彼此而言"DOMContentLoaded"
and "load"
事件。 “加载”是为了安全起见的备用事件,不需要。
- If
document.addEventListener
不存在,然后使用安装事件处理程序.attachEvent()
for "onreadystatechange"
and "onload"
events.
- In the
onreadystatechange
事件,检查是否document.readyState === "complete"
如果是这样,调用一个函数来触发所有准备好的处理程序。
- 在所有其他事件处理程序中,调用一个函数来触发所有就绪的处理程序。
- 在调用所有就绪处理程序的函数中,检查状态变量以查看我们是否已经触发。如果有,就什么也不做。如果我们还没有被调用,那么循环遍历准备好的函数数组并按照添加的顺序调用每个函数。设置一个标志来指示这些都已被调用,因此它们不会被执行多次。
- 清除函数数组,以便释放它们可能使用的任何闭包。
注册处理程序docReady()
保证按照注册顺序被解雇。
如果你打电话docReady(fn)
文档准备好后,回调将被安排在当前执行线程完成后立即执行setTimeout(fn, 1)
。这允许调用代码始终假设它们是稍后将调用的异步回调,即使稍后是 JS 当前线程完成后调用的,并且它保留调用顺序。