我有一个使用$(document).ready
的脚本,但它不使用jQuery中的任何其他内容。我想通过删除jQuery依赖项来减轻它。
如何在不使用jQuery的情况下实现自己的$(document).ready
功能?我知道使用window.onload
将不会是相同的,因为window.onload
在所有图像,帧等已经加载后触发。
有一个基于标准的替代品,DOMContentLoaded
得到了98% of browsers的支持,但不是IE8:
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
jQuery的本机函数比window.onload复杂得多,如下所示。
function bindReady(){
if ( readyBound ) return;
readyBound = true;
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
jQuery.ready();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
jQuery.ready();
}
});
// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && window == window.top ) (function(){
if ( jQuery.isReady ) return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch( error ) {
setTimeout( arguments.callee, 0 );
return;
}
// and execute any waiting functions
jQuery.ready();
})();
}
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
}
jQuery的答案对我来说非常有用。通过一点点重构,它很好地满足了我的需求。我希望它可以帮助其他任何人。
function onReady ( callback ){
var addListener = document.addEventListener || document.attachEvent,
removeListener = document.removeEventListener || document.detachEvent
eventName = document.addEventListener ? "DOMContentLoaded" : "onreadystatechange"
addListener.call(document, eventName, function(){
removeListener( eventName, arguments.callee, false )
callback()
}, false )
}
跨浏览器(旧浏览器)和简单的解决方案:
var docLoaded = setInterval(function () {
if(document.readyState !== "complete") return;
clearInterval(docLoaded);
/*
Your code goes here i.e. init()
*/
}, 30);
这是测试DOM就绪的最小代码片段,适用于所有浏览器(甚至是IE 8):
r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
看到这个answer。
只需将其添加到HTML页面的底部即可...
<script>
Your_Function();
</script>
因为,HTML文档是由上下解析的。
一旦DOM准备好,这个跨浏览器代码将调用一个函数:
var domReady=function(func){
var scriptText='('+func+')();';
var scriptElement=document.createElement('script');
scriptElement.innerText=scriptText;
document.body.appendChild(scriptElement);
};
以下是它的工作原理:
domReady
的第一行调用函数的toString
方法来获取传入函数的字符串表示形式,并将其包装在一个立即调用该函数的表达式中。domReady
的其余部分使用表达式创建一个脚本元素,并将其附加到文档的body
。body
的脚本标记。例如,如果您这样做:domReady(function(){alert();});
,以下内容将附加到body
元素:
<script>(function (){alert();})();</script>
请注意,这仅适用于用户定义的函数。以下不起作用:domReady(alert);
值得一看Rock Solid addEvent()和http://www.braksator.com/how-to-make-your-own-jquery。
以下是网站发生故障时的代码
function addEvent(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
EventCache.add(obj, type, fn);
}
else if (obj.attachEvent) {
obj["e"+type+fn] = fn;
obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
obj.attachEvent( "on"+type, obj[type+fn] );
EventCache.add(obj, type, fn);
}
else {
obj["on"+type] = obj["e"+type+fn];
}
}
var EventCache = function(){
var listEvents = [];
return {
listEvents : listEvents,
add : function(node, sEventName, fHandler){
listEvents.push(arguments);
},
flush : function(){
var i, item;
for(i = listEvents.length - 1; i >= 0; i = i - 1){
item = listEvents[i];
if(item[0].removeEventListener){
item[0].removeEventListener(item[1], item[2], item[3]);
};
if(item[1].substring(0, 2) != "on"){
item[1] = "on" + item[1];
};
if(item[0].detachEvent){
item[0].detachEvent(item[1], item[2]);
};
item[0][item[1]] = null;
};
}
};
}();
// Usage
addEvent(window, 'unload', EventCache.flush);
addEvent(window, 'load', function(){alert("I'm ready");});
这个解决方案怎么样?
// other onload attached earlier
window.onload=function() {
alert('test');
};
tmpPreviousFunction=window.onload ? window.onload : null;
// our onload function
window.onload=function() {
alert('another message');
// execute previous one
if (tmpPreviousFunction) tmpPreviousFunction();
};
与jQuery相比,使用JavaScript等价物总是好的。一个原因是要依赖的库少一个,它们比jQuery等价物快得多。
jQuery等价物的一个很棒的参考是http://youmightnotneedjquery.com/。
就你的问题而言,我从上面的链接中获取了以下代码:)唯一需要注意的是它只适用于Internet Explorer 9及更高版本。
function ready(fn) {
if (document.readyState != 'loading') {
fn();
}
else {
document.addEventListener('DOMContentLoaded', fn);
}
}
我们发现了一个快速而又脏的跨浏览器实现,我们可以通过最少的实现来解决大多数简单案例:
window.onReady = function onReady(fn){
document.body ? fn() : setTimeout(function(){ onReady(fn);},50);
};
此处提供的setTimeout / setInterval解决方案仅适用于特定情况。
该问题尤其出现在最新版本为8的旧版Internet Explorer中。
影响这些setTimeout / setInterval解决方案成功的变量是:
1) dynamic or static HTML
2) cached or non cached requests
3) size of the complete HTML document
4) chunked or non chunked transfer encoding
解决此特定问题的原始(本机Javascript)代码在此处:
https://github.com/dperini/ContentLoaded
http://javascript.nwbox.com/ContentLoaded (test)
这是jQuery团队构建其实现的代码。
编辑:
function ready(callback){
// in case the document is already rendered
if (document.readyState!='loading') callback();
// modern browsers
else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback);
// IE <= 8
else document.attachEvent('onreadystatechange', function(){
if (document.readyState=='complete') callback();
});
}
ready(function(){
// do something
});
取自https://plainjs.com/javascript/events/running-code-when-the-document-is-ready-15/
Another good domReady function here取自https://stackoverflow.com/a/9899701/175071
由于接受的答案远未完成,我将基于jQuery 1.6.2源码的jQuery.ready()
“准备好”的功能拼接在一起:
var ready = (function(){
var readyList,
DOMContentLoaded,
class2type = {};
class2type["[object Boolean]"] = "boolean";
class2type["[object Number]"] = "number";
class2type["[object String]"] = "string";
class2type["[object Function]"] = "function";
class2type["[object Array]"] = "array";
class2type["[object Date]"] = "date";
class2type["[object RegExp]"] = "regexp";
class2type["[object Object]"] = "object";
var ReadyObj = {
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
ReadyObj.readyWait++;
} else {
ReadyObj.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--ReadyObj.readyWait) || (wait !== true && !ReadyObj.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( ReadyObj.ready, 1 );
}
// Remember that the DOM is ready
ReadyObj.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --ReadyObj.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ ReadyObj ] );
// Trigger any bound ready events
//if ( ReadyObj.fn.trigger ) {
// ReadyObj( document ).trigger( "ready" ).unbind( "ready" );
//}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = ReadyObj._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( ReadyObj.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", ReadyObj.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", ReadyObj.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
_Deferred: function() {
var // callbacks list
callbacks = [],
// stored [ context , args ]
fired,
// to avoid firing when already doing so
firing,
// flag to know if the deferred has been cancelled
cancelled,
// the deferred itself
deferred = {
// done( f1, f2, ...)
done: function() {
if ( !cancelled ) {
var args = arguments,
i,
length,
elem,
type,
_fired;
if ( fired ) {
_fired = fired;
fired = 0;
}
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = ReadyObj.type( elem );
if ( type === "array" ) {
deferred.done.apply( deferred, elem );
} else if ( type === "function" ) {
callbacks.push( elem );
}
}
if ( _fired ) {
deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
}
}
return this;
},
// resolve with given context and args
resolveWith: function( context, args ) {
if ( !cancelled && !fired && !firing ) {
// make sure args are available (#8421)
args = args || [];
firing = 1;
try {
while( callbacks[ 0 ] ) {
callbacks.shift().apply( context, args );//shifts a callback, and applies it to document
}
}
finally {
fired = [ context, args ];
firing = 0;
}
}
return this;
},
// resolve with this as context and given arguments
resolve: function() {
deferred.resolveWith( this, arguments );
return this;
},
// Has this deferred been resolved?
isResolved: function() {
return !!( firing || fired );
},
// Cancel
cancel: function() {
cancelled = 1;
callbacks = [];
return this;
}
};
return deferred;
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ Object.prototype.toString.call(obj) ] || "object";
}
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( ReadyObj.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
ReadyObj.ready();
}
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
ReadyObj.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
ReadyObj.ready();
}
};
}
function ready( fn ) {
// Attach the listeners
ReadyObj.bindReady();
var type = ReadyObj.type( fn );
// Add the callback
readyList.done( fn );//readyList is result of _Deferred()
}
return ready;
})();
如何使用:
<script>
ready(function(){
alert('It works!');
});
ready(function(){
alert('Also works!');
});
</script>
我不确定这段代码的功能如何,但它在我的表面测试中运行良好。这花了很长时间,所以我希望你和其他人可以从中受益。
PS。:我建议compiling吧。
或者你可以使用http://dustindiaz.com/smallest-domready-ever:
function r(f){/in/.test(document.readyState)?setTimeout(r,9,f):f()}
r(function(){/*code to run*/});
或者本机函数,如果你只需要支持新的浏览器(与jQuery ready不同,如果在页面加载后添加它,则不会运行)
document.addEventListener('DOMContentLoaded',function(){/*fun code to run*/})
这是我使用的,它很快,涵盖了我认为的所有基础;适用于IE <9以外的所有内容。
(() => { function fn() {
// "On document ready" commands:
console.log(document.readyState);
};
if (document.readyState != 'loading') {fn()}
else {document.addEventListener('DOMContentLoaded', fn)}
})();
这似乎抓住了所有情况:
DOMContentLoaded事件在IE9和其他所有内容中都可用,因此我个人认为使用它是可以的。如果您没有将代码从ES2015转换为ES5,请将箭头函数声明重写为常规匿名函数。
如果要等到加载所有资源,显示所有图像等,则使用window.onload。
如果您不必支持非常旧的浏览器,即使外部脚本加载了async属性,也可以使用以下方法:
HTMLDocument.prototype.ready = new Promise(function(resolve) {
if(document.readyState != "loading")
resolve();
else
document.addEventListener("DOMContentLoaded", function() {
resolve();
});
});
document.ready.then(function() {
console.log("document.ready");
});
对于IE9 +:
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
这种方法是我能想到的最短路。
基于DOMContentLoaded事件的解决方案仅在脚本在文档之前加载时才有效,而此处建议的延迟检查确保代码始终执行,即使在稍后动态加载的脚本中也是如此,就像JQuery的文档准备好一样。
此代码与所有浏览器兼容(包括一些旧版本,适用于IE6和Safari for Windows)。
(function ready() {
if (!document.body) {setTimeout(ready, 50); return;}
// Document is ready here
})();
jQuery
中的ready函数做了很多事情。坦率地说,除非你的网站产量非常小,否则我没有看到更换它的重点。 jQuery
是一个非常小的库,它可以处理您以后需要的各种跨浏览器。
无论如何,在这里发布它没什么意义,只需打开jQuery
并查看bindReady
方法。
它首先根据事件模型调用document.addEventListener("DOMContentLoaded")
或document.attachEvent('onreadystatechange')
,然后从那里继续。
试试这个:
function ready(callback){
if(typeof callback === "function"){
document.addEventListener("DOMContentLoaded", callback);
window.addEventListener("load", callback);
}else{
throw new Error("Sorry, I can not run this!");
}
}
ready(function(){
console.log("It worked!");
});
function onDocReady(fn){
$d.readyState!=="loading" ? fn():document.addEventListener('DOMContentLoaded',fn);
}
function onWinLoad(fn){
$d.readyState==="complete") ? fn(): window.addEventListener('load',fn);
}
当HTML dom准备好完全访问/解析/操作时,onDocReady提供回调。
onWinLoad在所有内容都已加载时提供回调(图像等)
(function(f){
if(document.readyState != "loading") f();
else document.addEventListener("DOMContentLoaded", f);
})(function(){
console.log("The Document is ready");
});
大多数vanilla JS Ready函数都没有考虑在文档加载后设置DOMContentLoaded
处理程序的场景 - 这意味着该函数永远不会运行。如果你在DOMContentLoaded
外部脚本(async
)中寻找<script async src="file.js"></script>
,就会发生这种情况。
仅当文档的DOMContentLoaded
不是readyState
或interactive
时,下面的代码才会检查complete
。
var DOMReady = function(callback) {
document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback());
};
DOMReady(function() {
//DOM ready!
});
如果你想支持IE以及:
var DOMReady = function(callback) {
if (document.readyState === "interactive" || document.readyState === "complete") {
callback();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', callback());
} else if (document.attachEvent) {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading') {
callback();
}
});
}
};
DOMReady(function() {
// DOM ready!
});
三种选择:
script
是正文的最后一个标记,则DOM将在脚本标记执行之前就绪的onreadystatechange
document.onreadystatechange = function () {
if (document.readyState == "complete") {
// document is ready. Do your stuff here
}
}
资料来源:MDN
DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() {
console.log('document is ready. I can sleep now');
});
关注石器时代的浏览器:转到jQuery源代码并使用ready
函数。在这种情况下,你没有解析+执行整个库,你只做了很小的一部分。
这是一个很好的https://stackoverflow.com/a/11810957/185565穷人的解决方案。一条评论认为,在紧急情况下应该采取救助措施。这是我的修改。
function doTheMagic(counter) {
alert("It worked on " + counter);
}
// wait for document ready then call handler function
var checkLoad = function(counter) {
counter++;
if (document.readyState != "complete" && counter<1000) {
var fn = function() { checkLoad(counter); };
setTimeout(fn,10);
} else doTheMagic(counter);
};
checkLoad(0);
将<script>/*JavaScript code*/</script>
放在关闭的</body>
标签之前。
不可否认,这可能不适合每个人的目的,因为它需要更改HTML文件,而不是仅仅在JavaScript文件中执行la document.ready
,但仍然......
穷人的解决方案:
var checkLoad = function() {
document.readyState !== "complete" ? setTimeout(checkLoad, 11) : alert("loaded!");
};
checkLoad();
添加了这个,我想更好一点,拥有范围,非递归
(function(){
var tId = setInterval(function() {
if (document.readyState == "complete") onComplete()
}, 11);
function onComplete(){
clearInterval(tId);
alert("loaded!");
};
})()
我用这个:
document.addEventListener("DOMContentLoaded", function(event) {
//Do work
});
注意:这可能仅适用于较新的浏览器,尤其是:http://caniuse.com/#feat=domcontentloaded
真的,如果你只关心Internet Explorer 9+,这段代码足以取代jQuery.ready
:
document.addEventListener("DOMContentLoaded", callback);
如果你担心Internet Explorer 6和一些非常奇怪和罕见的浏览器,这将工作:
domReady: function (callback) {
// Mozilla, Opera and WebKit
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", callback, false);
// If Internet Explorer, the event model is used
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
if (document.readyState === "complete" ) {
callback();
}
});
// A fallback to window.onload, that will always work
} else {
var oldOnload = window.onload;
window.onload = function () {
oldOnload && oldOnload();
callback();
}
}
},
很久以前就问过这个问题了。对于任何刚看到这个问题的人来说,现在有一个名为"you might not need jquery"的站点,它根据所需的IE支持级别进行分解 - 所有jquery的功能,并提供了一些替代的,更小的库。
根据you might not need jquery的IE8文档准备脚本
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();
});
}
我最近在移动网站上使用它。这是John Resig的“Pro JavaScript Techniques”简化版。这取决于addEvent。
var ready = ( function () {
function ready( f ) {
if( ready.done ) return f();
if( ready.timer ) {
ready.ready.push(f);
} else {
addEvent( window, "load", isDOMReady );
ready.ready = [ f ];
ready.timer = setInterval(isDOMReady, 13);
}
};
function isDOMReady() {
if( ready.done ) return false;
if( document && document.getElementsByTagName && document.getElementById && document.body ) {
clearInterval( ready.timer );
ready.timer = null;
for( var i = 0; i < ready.ready.length; i++ ) {
ready.ready[i]();
}
ready.ready = null;
ready.done = true;
}
}
return ready;
})();