javascript - ready原生 - window.onready
jQuery的$.ready()的纯JavaScript等价物-如何在页面/ DOM准备好时调用函数 (7)
准备
function ready(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();}
使用像
ready(function(){
//some code
});
用于自我调用代码
(function(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();})(function(){
//Some Code here
//DOM is avaliable
//var h1s = document.querySelector("h1");
});
支持:IE9 +
这个问题在这里已经有了答案:
好吧,这可能只是一个愚蠢的问题,尽管我确信还有很多其他人不时提出同样的问题。 我,我只是想100%肯定它的方式。 用jQuery我们都知道这很棒
$('document').ready(function(){});
然而,假设我想运行一个用标准JavaScript编写的函数,而没有库支持它,并且我希望在页面准备好处理它时立即启动一个函数。 什么是正确的方法来解决这个问题?
我知道我可以这样做:
window.onload="myFunction()";
...或者我可以使用body
标记:
<body onload="myFunction()">
......或者我甚至可以在页面的底部尝试所有内容,但最终的body
或html
标签如下所示:
<script type="text/javascript">
myFunction();
</script>
什么是以jQuery的$.ready()
方式发布一个或多个函数的跨浏览器(旧/新)兼容方法?
HubSpot中的优秀人员拥有一个资源,您可以在其中找到纯粹的Javascript方法来实现很多jQuery优点 - 包括ready
http://youmightnotneedjquery.com/#ready
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading')
fn();
});
}
}
示例内联用法:
ready(function() { alert('hello'); });
你的方法(在关闭body标签之前放置脚本)
<script>
myFunction()
</script>
</body>
</html>
是支持新老浏览器的可靠方法。
在没有为您提供所有跨浏览器兼容性的框架的情况下,最简单的方法就是在本体的最后调用代码。 这比onload
处理程序执行速度更快,因为它仅等待DOM准备就绪,而不是等待所有图像加载。 而且,这适用于每个浏览器。
<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>
如果你真的不想这样做,并且你需要跨浏览器兼容性,并且你不想等待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为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/ : http://jsfiddle.net/jfriend00/YfD3C/
以下是它的工作原理的总结:
- 创建一个IIFE (立即调用函数表达式),以便我们可以拥有非公共状态变量。
- 声明一个公共函数
docReady(fn, context)
- 当
docReady(fn, context)
,检查ready处理程序是否已经被触发。 如果是这样,只需在JS的这个线程以setTimeout(fn, 1)
结束之后安排新添加的回调即可触发。 - 如果就绪处理程序尚未触发,则将此新回调添加到稍后调用的回调列表中。
- 检查文档是否已准备就绪。 如果是,请执行所有准备好的处理程序。
- 如果我们尚未安装事件侦听器,但尚未知道文档何时准备就绪,请立即安装它们。
- 如果
document.addEventListener
存在,则使用.addEventListener()
为"DOMContentLoaded"
和"load"
事件安装事件处理程序。 “负载”是安全的备份事件,不应该需要。 - 如果
document.addEventListener
不存在,则为"onreadystatechange"
和"onload"
事件安装使用.attachEvent()
事件处理程序。 - 在
onreadystatechange
事件中,检查document.readyState === "complete"
是否document.readyState === "complete"
,如果是,请调用一个函数来触发所有就绪处理程序。 - 在所有其他事件处理程序中,调用一个函数来触发所有就绪处理程序。
- 在调用所有就绪处理程序的函数中,检查一个状态变量以查看我们是否已经被触发。 如果我们有,什么也不做。 如果我们还没有被调用,然后遍历已准备函数的数组,并按照它们添加的顺序调用每个函数。 设置一个标志来表明这些全部被调用,所以它们永远不会被执行多次。
- 清除函数数组,以便它们可能使用的任何闭包都可以被释放。
通过docReady()
注册的处理程序保证按照它们注册的顺序被解雇。
如果在文档已准备好之后调用docReady(fn)
,则只要当前执行的线程使用setTimeout(fn, 1)
完成,就会安排回调执行。 这允许调用代码始终认为它们是将在稍后调用的异步回调,即使稍后只要JS的当前线程完成并且它保留了调用顺序。
我不太清楚你在问什么,但也许这可以提供帮助:
window.onload = function(){
// Code. . .
}
要么:
window.onload = main;
function main(){
// Code. . .
}
我想在这里提到一些可能的方法,以及可在所有浏览器中使用的纯JavaScript技巧 :
// with jQuery
$(document).ready(function(){ /* ... */ });
// shorter jQuery version
$(function(){ /* ... */ });
// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){
// your code goes here
}, false);
// and here's the trick (works everywhere)
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
// use like
r(function(){
alert('DOM Ready!');
});
正如原始作者所解释的,这里的技巧是我们正在检查document.readyState属性。 如果它包含字符串(如未uninitialized
和loading
,前两个DOM就绪状态中的5个),我们设置超时并再次检查。 否则,我们执行传递的函数。
这里是jsFiddle , 适用于所有浏览器都可以使用的技巧。
感谢Tutorialzine将它包含在他们的书中。
这是一个清理,非评估版Ram-swaroop's “适用于所有浏览器”的多种版本 - 适用于所有浏览器!
function onReady(yourMethod) {
var readyStateCheckInterval = setInterval(function() {
if (document && document.readyState === 'complete') { // Or 'interactive'
clearInterval(readyStateCheckInterval);
yourMethod();
}
}, 10);
}
// use like
onReady(function() { alert('hello'); } );
然而,它等待额外的10毫秒运行,所以这是一个更复杂的方式,不应该这样做:
function onReady(yourMethod) {
if (document.readyState === 'complete') { // Or also compare to 'interactive'
setTimeout(yourMethod, 1); // Schedule to run immediately
}
else {
readyStateCheckInterval = setInterval(function() {
if (document.readyState === 'complete') { // Or also compare to 'interactive'
clearInterval(readyStateCheckInterval);
yourMethod();
}
}, 10);
}
}
// Use like
onReady(function() { alert('hello'); } );
// Or
onReady(functionName);
另请参见如何在没有框架的情况下检查DOM是否已准备就绪? 。