了jQuery,我们都知道奇妙的.ready()功能:
.ready()
$('document').ready(function(){});
但是,假设我想运行一个用标准 JavaScript 编写的函数,没有库支持它,并且我想在页面准备好处理它时立即启动一个函数。解决这个问题的正确方法是什么?
我知道我可以做到:
window.onload="myFunction()";
或者我可以使用body标签:
body
<body onload="myFunction()">
或者我什至可以在所有内容之后尝试在页面底部,但结尾body或html标签如下:
html
<script type="text/javascript"> myFunction(); </script>
以 jQuery 之类的方式发布一个或多个函数的跨浏览器(旧/新)兼容方法是$.ready()什么?
$.ready()
在没有为您提供所有跨浏览器兼容性的框架的情况下,最简单的事情就是在正文末尾调用您的代码。这比onload处理程序执行起来更快,因为它只等待 DOM 准备好,而不是等待所有图像加载。而且,这适用于每个浏览器。
onload
<!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()可以从任何地方调用的类似 jQuery 的方法(无需担心调用脚本的位置),你可以使用这样的东西:
$(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); } }
用法:
docReady(function() { // DOM is loaded and ready for manipulation here });
如果您需要完全跨浏览器兼容性(包括旧版本的 IE)并且您不想等待window.onload,那么您可能应该去看看像 jQuery 这样的框架是如何实现它的$(document).ready()方法的。根据浏览器的功能,它相当复杂。
window.onload
让您稍微了解一下 jQuery 的作用(无论放置脚本标签的地方都可以使用)。
如果支持,它会尝试标准:
document.addEventListener('DOMContentLoaded', fn, false);
回退到:
window.addEventListener('load', fn, false )
或者对于旧版本的 IE,它使用:
document.attachEvent("onreadystatechange", fn);
window.attachEvent("onload", fn);
而且,在 IE 代码路径中有一些我不太遵循的解决方法,但它看起来与框架有关。
.ready()这是用纯 javascript 编写的 jQuery 的完全替代品:
(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
// 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/
以下是其工作原理的摘要:
docReady(fn, context)
setTimeout(fn, 1)
document.addEventListener
.addEventListener()``"DOMContentLoaded"``"load"
.attachEvent()
"onreadystatechange"
"onload"
onreadystatechange
document.readyState === "complete"
注册的处理程序docReady()保证按照注册的顺序被触发。
docReady()
如果您docReady(fn)在文档已经准备好之后调用,回调将被安排在当前执行线程完成后立即使用setTimeout(fn, 1). 这允许调用代码始终假定它们是稍后将调用的异步回调,即使稍后是 JS 的当前线程完成并且它保留调用顺序。
docReady(fn)