好的,这可能只是一个愚蠢的问题,尽管我敢肯定会有很多其他人不时问同样的问题。我,我只是想以任何一种方式100%确定它。有了jQuery,我们都知道精彩之处
$('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),如果您希望能够实现类似jQuery的$(document).ready()方法,可以从任何地方调用(而不必担心调用脚本的位置),您可以只使用以下内容:
$(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的功能(无论放置script标记的位置都可以使用jQuery)。
如果支持,它将尝试标准:
document.addEventListener('DOMContentLoaded', fn, false);
后退到:
window.addEventListener('load', fn, false )
或对于较旧版本的IE,它使用:
document.attachEvent("onreadystatechange", fn);
window.attachEvent("onload", fn);
而且,我不太了解IE代码路径中的一些变通办法,但看起来它与框架有关。
这是.ready()用普通javascript编写的jQuery的完全替代:
.ready()
(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);
// 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
以下是其工作原理的摘要:
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)