我有一个使用$(document).ready的脚本,但它不使用jQuery中的任何其他内容。我想通过删除jQuery依赖项来减轻它。
如何在不使用jQuery的情况下实现我自己的$(document).ready功能?我知道,使用window.onload将不同,因为window.onlead在加载所有图像、帧等后启动。
我有一个使用$(document).ready的脚本,但它不使用jQuery中的任何其他内容。我想通过删除jQuery依赖项来减轻它。
如何在不使用jQuery的情况下实现我自己的$(document).ready功能?我知道,使用window.onload将不同,因为window.onlead在加载所有图像、帧等后启动。
有一种基于标准的替代品DOMContentLoaded,99%以上的浏览器都支持它,但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中的ready函数做了很多事情。坦率地说,除非你的网站有惊人的小输出,否则我看不出替换它的意义。jQuery是一个非常小的库,它处理您稍后需要的各种跨浏览器的事情。
无论如何,在这里发布它没有什么意义,只需打开jQuery并查看bindReady方法。
它首先根据事件模型调用document.addEventListener(“DOMContentLoaded”)或document.attachEvent(“unreadystatechange”),然后继续。
将<script>/*JavaScript代码*/</script>放在结束</body>标记之前。
诚然,这可能不符合每个人的目的,因为它需要更改HTML文件,而不仅仅是在JavaScript文件中做一些事情,比如document.ready,但是。。。
我最近在一个移动网站上使用这个。这是John Resig的简化版“Pro JavaScript技术”。它取决于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;
})();
编辑:
2023更新,请使用此项:
function ready(fn) {
if (document.readyState !== 'loading') {
fn();
return;
}
document.addEventListener('DOMContentLoaded', fn);
}
发件人:https://youmightnotneedjquery.com/
这里是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/
另一个很好的domReady函数来自https://stackoverflow.com/a/9899701/175071
由于被接受的答案还远远没有完成,我根据jQuery1.6.2的源代码拼接了一个“ready”函数,如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.:我建议编译它。
或者你可以使用http://dustindiaz.com/smallest-domready-ever:
function r(f){/in/.test(document.readyState)?setTimeout(r,9,f):f()}
r(function(){/*code to run*/});
如果您只需要支持新的浏览器,则使用本机函数(与jQuery就绪不同,如果您在页面加载后添加此函数,则不会运行此函数)
document.addEventListener('DOMContentLoaded',function(){/*fun code to run*/})
值得在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");});
穷人的解决方案:
var checkLoad = function() {
document.readyState !== "complete" ? setTimeout(checkLoad, 11) : alert("loaded!");
};
checkLoad();
查看Fiddle
添加了这个,我想更好一点,自己的范围,非递归
(function(){
var tId = setInterval(function() {
if (document.readyState == "complete") onComplete()
}, 11);
function onComplete(){
clearInterval(tId);
alert("loaded!");
};
})()
查看Fiddle
这个解决方案怎么样?
// 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的回答对我很有用。经过一点重构,它很好地满足了我的需求。我希望这对其他人有所帮助。
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 )
}
三个选项:
如果script是主体的最后一个标记,则DOM将在脚本标记执行之前准备就绪当DOM就绪时,“readyState”将变为“complete”将所有内容置于“DOMContentLoaded”事件侦听器下
在准备状态更改时
document.onreadystatechange = function () {
if (document.readyState == "complete") {
// document is ready. Do your stuff here
}
}
来源:MDN
DOMContentLoaded(DOM内容已加载)
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);
如果你想支持Internet Explorer 7+(没有怪癖、兼容性和其他问题),最后一个Chrome、最后一个Safari、最后一次Firefox和没有iframes,这就足够了:
is_loaded = false
callbacks = []
loaded = ->
is_loaded = true
for i in [0...callbacks.length]
callbacks[i].call document
callbacks = []
content_loaded = ->
document.removeEventListener "DOMContentLoaded", content_loaded, true
loaded()
state_changed = ->
if document.readyState is "complete"
document.detachEvent "onreadystatechange", state_changed
loaded()
if !!document.addEventListener
document.addEventListener "DOMContentLoaded", content_loaded, true
else
document.attachEvent "onreadystatechange", state_changed
dom_ready = (callback) ->
if is_loaded
callback.call document
else
callbacks.push callback
跨浏览器(旧浏览器也是)和简单的解决方案:
var docLoaded = setInterval(function () {
if(document.readyState !== "complete") return;
clearInterval(docLoaded);
/*
Your code goes here i.e. init()
*/
}, 30);
在jsfiddle中显示警报
我使用这个:
document.addEventListener("DOMContentLoaded", function(event) {
//Do work
});
注意:这可能只适用于较新的浏览器,尤其是以下浏览器:http://caniuse.com/#feat=domcontentloaded
如果您正在加载BODY底部附近的jQuery,但在编写jQuery(<func>)或jQuery(document).ready(<func>)时遇到问题,请在Github上查看jqShim。
与其重新创建自己的文档就绪函数,它只需保留这些函数,直到jQuery可用,然后按预期继续jQuery。将jQuery移动到主体底部的目的是加快页面加载速度,您仍然可以通过在模板头部内联jqShim.min.js来实现这一点。
最后我写了这段代码,将WordPress中的所有脚本都移到了页脚,而现在只有这段填充码直接位于页眉中。
编辑@duskwuff以支持Internet Explorer 8。不同的是,使用匿名函数对regex和setTimeout的函数测试进行了新的调用。
此外,我将超时设置为99。
function ready(f){/in/.test(document.readyState)?setTimeout(function(){ready(f);},99):f();}
我们发现了一个快速而肮脏的跨浏览器实现,它可以用最少的实现实现大多数简单情况:
window.onReady = function onReady(fn){
document.body ? fn() : setTimeout(function(){ onReady(fn);},50);
};
此处提供的setTimeout/setInterval解决方案仅在特定情况下有效。
该问题在旧版本的Internet Explorer(最高8版)中尤为突出。
影响这些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团队构建其实现的代码。
实际上,如果您只关心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();
}
}
},
一旦DOM就绪,此跨浏览器代码将调用函数:
var domReady=function(func){
var scriptText='('+func+')();';
var scriptElement=document.createElement('script');
scriptElement.innerText=scriptText;
document.body.appendChild(scriptElement);
};
以下是它的工作原理:
domReady的第一行调用函数的toString方法,以获取传入函数的字符串表示形式,并将其包装在立即调用该函数的表达式中。domReady的其余部分使用表达式创建一个脚本元素,并将其附加到文档正文中。DOM就绪后,浏览器运行附加到主体的脚本标记。
例如,如果您这样做:domReady(function(){alert();});,以下内容将附加到body元素:
<script>(function (){alert();})();</script>
注意,这只适用于用户定义的函数。以下命令不起作用:domReady(警报);
这个问题很久以前就被问过了。对于任何看到这个问题的人来说,现在有一个名为“您可能不需要jquery”的网站,它按所需的IE支持级别分解了jquery的所有功能,并提供了一些替代的、较小的库。
IE8文档就绪脚本,根据您可能不需要jquery
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();
});
}
以下是测试DOM就绪的最小代码片段,它适用于所有浏览器(甚至IE 8):
r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
看到这个答案。
简而言之,我们可以使用JavaScript方法来代替jQuery中使用的$(document).ready():
<script>
document.addEventListener("DOMContentLoaded", function_name, false);
function function_name(){
statements;
}
</script>
因此,当页面准备就绪(即DOMContentLoaded)时,将调用函数function_name()。
对于IE9+:
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
与jQuery相比,使用JavaScript等价物总是很好的。一个原因是依赖的库少了一个,而且它们比jQuery等同物快得多。
jQuery等价物的一个极好的参考是http://youmightnotneedjquery.com/.
就您的问题而言,我从上面的链接中获取了以下代码:)唯一需要注意的是,它仅适用于Internet Explorer 9及更高版本。
function ready(fn) {
if (document.readyState != 'loading') {
fn();
}
else {
document.addEventListener('DOMContentLoaded', fn);
}
}
这是我使用的,它很快,涵盖了我认为的所有基础;适用于除IE<9以外的所有情况。
(() => { function fn() {
// "On document ready" commands:
console.log(document.readyState);
};
if (document.readyState != 'loading') {fn()}
else {document.addEventListener('DOMContentLoaded', fn)}
})();
这似乎适用于所有情况:
如果DOM已经就绪(如果DOM不是“加载”,而是“交互式”或“完成”),则立即激发如果DOM仍在加载,它将在DOM可用(交互式)。
DOMContentLoaded事件在IE9和其他所有版本中都可用,所以我个人认为使用它是可以的。如果您没有将代码从ES2015传输到ES5,请将箭头函数声明重写为常规匿名函数。
如果您想等到加载所有资产、显示所有图像等,请改用window.onload。
如果您不必支持非常旧的浏览器,即使在外部脚本加载了异步属性时,也可以使用以下方法:
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");
});
我只使用:
setTimeout(function(){
//reference/manipulate DOM here
});
而且与上面的答案中的document.addEventListener(“DOMContentLoaded”//等不同,它的工作时间可以追溯到IE9——http://caniuse.com/#search=DOMContentLoaded仅表示最近的IE11。
有趣的是,我在2009年偶然发现了这个setTimeout解决方案:检查DOM的准备是否过度?,我的意思是“使用各种框架的更复杂的方法来检查DOM的就绪性是否过分”。
我对这种技术为什么有效的最好解释是,当使用这样一个setTimeout的脚本到达时,DOM正处于解析过程中,因此setTimeout中的代码的执行会延迟到该操作完成。
试试看:
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(f){
if(document.readyState != "loading") f();
else document.addEventListener("DOMContentLoaded", f);
})(function(){
console.log("The Document is ready");
});
大多数普通的JS Ready函数都不考虑在文档加载后设置DOMContentLoaded处理程序的情况——这意味着函数永远不会运行。如果在异步外部脚本(<script async src=“file.js”></script>)中查找DOMContentLoaded,则可能会发生这种情况。
只有当文档的readyState尚未交互或完成时,下面的代码才会检查DOMContentLoaded。
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!
});
最小且100%工作
我已经从PlainJS中选择了答案,它对我来说很好。它扩展了DOMContentLoaded,因此它可以在所有浏览器中被接受。
此函数等效于jQuery的$(document).ready()方法:
document.addEventListener('DOMContentLoaded', function(){
// do something
});
然而,与jQuery不同的是,这段代码只能在现代浏览器中正常运行(IE>8),如果在插入此脚本时(例如通过Ajax)已经呈现了文档,则无法正常运行。因此,我们需要稍微扩展一下:
function run() {
// do something
}
// in case the document is already rendered
if (document.readyState!='loading') run();
// modern browsers
else if (document.addEventListener)
document.addEventListener('DOMContentLoaded', run);
// IE <= 8
else document.attachEvent('onreadystatechange', function(){
if (document.readyState=='complete') run();
});
这基本上涵盖了所有的可能性,是jQuery助手的可行替代品。
现在是2020年,<script>标签具有defer属性。
例如:
<script src="demo_defer.js" defer></script>
它指定当页面完成解析时执行脚本。
https://www.w3schools.com/tags/att_script_defer.asp
比较
这里(在下面的片段中)是所选择的可用浏览器“内置”方法及其执行顺序的比较。评论
任何现代浏览器都不支持document.onload(X)(从不触发事件)如果您使用<body onload=“bodyOnLoad()”>(F),同时使用window.onload(E),则只执行第一个(因为它会覆盖第二个)<body onload=“…”>(F)中给定的事件处理程序由附加的onload函数包装document.onreadystatechange(D)不覆盖document.addEventListener('readystatechange'…)(C)可能是因为类似XYZevent的方法独立于addEventListener队列(允许添加多个侦听器)。在执行这两个处理程序之间可能不会发生任何事情。所有脚本都在控制台中写入时间戳,但也可以访问div的脚本也在主体中写入时间标记(在脚本执行后单击“FullPage”链接查看)。解决方案readystatechange(C,D)由浏览器执行多次,但针对不同的文档状态:loading-文档正在加载(没有在代码段中激发)交互式-文档在DOMContentLoaded之前被解析和激发完成-加载文档和资源,在加载body/window之前激发
<html><head><脚本>//溶液Aconsole.log(`[timestamp:${Date.now()}]A:Head脚本`);//溶液Bdocument.addEventListener(“DOMContentLoaded”,()=>{print(`[时间戳:${Date.now()}]B:DOMContentLoaded`);});//溶液Cdocument.addEventListener('readystatechange',()=>{print(`[时间戳:${Date.now()}]C:就绪状态:${document.ReadyState}`);});//溶液Ddocument.onreadystatechange=s=>{print(`[时间戳:${Date.now()}]D:document.onrreadystatechange就绪状态:${document.ReadyState}`)};//解决方案E(从未执行)window.onload=()=>{print(`E:<body onload=“…”>覆盖此处理程序`);};//溶液F函数体OnLoad(){print(`[timestamp:${Date.now()}]F:<body onload='…'>`);infoAboutOnLoad();//其他信息}//溶液Xdocument.onload=()=>{print(“document.onlead从未启动”)};//助手函数打印(txt){console.log(txt);如果(mydiv)mydiv.innerHTML+=txt.replace('<','<;').replace('>','>;')+'<br>';}函数infoAboutOnLoad(){console.log(“window.onload(重写后):”,(“”+document.body.onload).replace(/\s+/g,“”));console.log(`body.onload==window.onload-->${document.body.onload==window.onload}`);}console.log(“window.onload(覆盖前):”,(“”+document.body.onload).replace(/\s+/g,“”));</script></head><body onload=“bodyOnLoad()”><div id=“mydiv”></div><!-- 此脚本必须位于<body>-->的底部<脚本>//溶液Gprint(`[timestamp:${Date.now()}]G:<body>底部脚本`);</script></body></html>
适用于所有已知的浏览器(通过BrowserStack测试)。IE6+、Safari 1+、Chrome 1+、Opera等。使用DOMContentLoaded,带有document.dococumentElement.doScroll()和window.onload的回退。
/*! https://github.com/Kithraya/DOMContentLoaded v1.2.6 | MIT License */
DOMContentLoaded.version = "1.2.6";
function DOMContentLoaded() { "use strict";
var ael = 'addEventListener', rel = 'removeEventListener', aev = 'attachEvent', dev = 'detachEvent';
var alreadyRun = false, // for use in the idempotent function ready()
funcs = arguments;
// old versions of JS return '[object Object]' for null.
function type(obj) { return (obj === null) ? 'null' : Object.prototype.toString.call(obj).slice(8,-1).toLowerCase() }
function microtime() { return + new Date() }
/* document.readyState === 'complete' reports correctly in every browser I have tested, including IE.
But IE6 to 10 don't return the correct readyState values as per the spec:
readyState is sometimes 'interactive', even when the DOM isn't accessible in IE6/7 so checking for the onreadystatechange event like jQuery does is not optimal
readyState is complete at basically the same time as 'window.onload' (they're functionally equivalent, within a few tenths of a second)
Accessing undefined properties of a defined object (document) will not throw an error (in case readyState is undefined).
*/
// Check for IE < 11 via conditional compilation
/// values: 5?: IE5, 5.5?: IE5.5, 5.6/5.7: IE6/7, 5.8: IE8, 9: IE9, 10: IE10, 11*: (IE11 older doc mode), undefined: IE11 / NOT IE
var jscript_version = Number( new Function("/*@cc_on return @_jscript_version; @*\/")() ) || NaN;
// check if the DOM has already loaded
if (document.readyState === 'complete') { ready(null); return; } // here we send null as the readyTime, since we don't know when the DOM became ready.
if (jscript_version < 9) { doIEScrollCheck(); return; } // For IE<9 poll document.documentElement.doScroll(), no further actions are needed.
/*
Chrome, Edge, Firefox, IE9+, Opera 9+, Safari 3.1+, Android Webview, Chrome for Android, Edge Mobile,
Firefox for Android 4+, Opera for Android, iOS Safari, Samsung Internet, etc, support addEventListener
And IE9+ supports 'DOMContentLoaded'
*/
if (document[ael]) {
document[ael]("DOMContentLoaded", ready, false);
window[ael]("load", ready, false); // fallback to the load event in case addEventListener is supported, but not DOMContentLoaded
} else
if (aev in window) { window[aev]('onload', ready);
/* Old Opera has a default of window.attachEvent being falsy, so we use the in operator instead
https://dev.opera.com/blog/window-event-attachevent-detachevent-script-onreadystatechange/
Honestly if somebody is using a browser so outdated AND obscure (like Opera 7 where neither addEventListener
nor "DOMContLoaded" is supported, they deserve to wait for the full page).
I CBA testing whether readyState === 'interactive' is truly interactive in browsers designed in 2003. I just assume it isn't (like in IE6-8).
*/
} else { // fallback to queue window.onload that will always work
addOnload(ready);
}
// This function allows us to preserve any original window.onload handlers (in super old browsers where this is even necessary),
// while keeping the option to chain onloads, and dequeue them.
function addOnload(fn) { var prev = window.onload; // old window.onload, which could be set by this function, or elsewhere
// we add a function queue list to allow for dequeueing
// addOnload.queue is the queue of functions that we will run when when the DOM is ready
if ( type( addOnload.queue ) !== 'array') { addOnload.queue = [];
if ( type(prev) === 'function') { addOnload.queue.push( prev ); } // add the previously defined event handler
}
if (typeof fn === 'function') { addOnload.queue.push(fn) }
window.onload = function() { // iterate through the queued functions
for (var i = 0; i < addOnload.queue.length; i++) { addOnload.queue[i]() }
};
}
// remove a queued window.onload function from the chain (simplified);
function dequeueOnload(fn) { var q = addOnload.queue, i = 0;
// sort through the queued functions in addOnload.queue until we find `fn`
if (type( q ) === 'array') { // if found, remove from the queue
for (; i < q.length; i++) { ;;(fn === q[i]) ? q.splice(i, 1) : 0; } // void( (fn === q[i]) ? q.splice(i, 1) : 0 )
}
}
function ready(ev) { // idempotent event handler function
if (alreadyRun) {return} alreadyRun = true;
// this time is when the DOM has loaded (or if all else fails, when it was actually possible to inference the DOM has loaded via a 'load' event)
// perhaps this should be `null` if we have to inference readyTime via a 'load' event, but this functionality is better.
var readyTime = microtime();
detach(); // detach any event handlers
// run the functions
for (var i=0; i < funcs.length; i++) { var func = funcs[i];
if (type(func) === 'function') {
func.call(document, { 'readyTime': (ev === null ? null : readyTime), 'funcExecuteTime': microtime() }, func);
// jquery calls 'ready' with `this` being set to document, so we'll do the same.
}
}
}
function detach() {
if (document[rel]) {
document[rel]("DOMContentLoaded", ready); window[rel]("load", ready);
} else
if (dev in window) { window[dev]("onload", ready); }
else {
dequeueOnload(ready);
}
}
function doIEScrollCheck() { // for use in IE < 9 only.
if ( window.frameElement ) {
// we're in an <iframe> or similar
// the document.documentElemeent.doScroll technique does not work if we're not at the top-level (parent document)
try { window.attachEvent("onload", ready); } catch (e) { } // attach to onload if were in an <iframe> in IE as there's no way to tell otherwise
return;
}
try {
document.documentElement.doScroll('left'); // when this statement no longer throws, the DOM is accessible in old IE
} catch(error) {
setTimeout(function() {
(document.readyState === 'complete') ? ready() : doIEScrollCheck();
}, 50);
return;
}
ready();
}
}
用法:
<script>
DOMContentLoaded(function(e) { console.log(e) });
</script>
现在你应该使用模块。将代码放入模块的默认函数中,并将该函数导入脚本元素。
客户端.js:
export default function ()
{
alert ("test");
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<script type="module">
import main from './client.js';
main ();
</script>
</body>
</html>
2022版本
2022年,您需要做的就是将defer属性放在脚本上,并将其加载到头部!
参考:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-推迟
<!doctype html>
<html>
<head>
<script src="/script.js" defer></script>
</head>
<body>
<p>In 2022, all you need to do is put the defer attribute on your script, and load it in the head!</p>
</body>
</html>
使用纯JavaScript的最简单方法。没有jQuery:
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
});