如何检测DOM准备并添加没有jQuery的类? [英] How can I detect DOM ready and add a class without jQuery?
问题描述
我想在不使用jQuery的情况下重写这一行,因此可以更快地应用(并且在下载jQuery库之前)。该行是......
I want to rewrite this line without using jQuery so it can be applied quicker (and before the downloading of the jQuery library). The line is...
$(document).ready(function() { $('body').addClass('javascript'); });
如果我将它添加到 html
元素相反,我可以放弃DOM准备好的部分吗?但有一个问题是验证器不喜欢 html
元素上的class属性,即使它是用JS插入的。
If I added it to the html
element instead, would I be able to leave off the DOM ready part? One problem with this though is the validator doesn't like the class attribute on the html
element, even if it is inserted with JS.
那么,如果没有jQuery,我将如何重写呢?
So, how would I rewrite that without jQuery?
推荐答案
如果你想重现jQuery的 document.ready
事件,您可以使用 onreadystatechange
或 DOMContentLoaded
适用的事件:
If you want to reproduce the jQuery's document.ready
event, you can use the onreadystatechange
or DOMContentLoaded
events where applicable:
function domReady () {
document.body.className += " javascript";
// ...
}
// Mozilla, Opera, Webkit
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false);
domReady();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
domReady();
}
});
}
这篇关于如何检测DOM准备并添加没有jQuery的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!