How Can I Detect Dom Ready And Add A Class Without Jquery?
Solution 1:
If you want to reproduce the jQuery's document.ready
event, you can use the onreadystatechange
or DOMContentLoaded
events where applicable:
functiondomReady () {
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
} elseif ( document.attachEvent ) {
// ensure firing before onloaddocument.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
domReady();
}
});
}
Solution 2:
I dont know about vanilla JS, but you can write:
document.getElementsByTagName('body')[0].className += ' javascript';
at the bottom of the page (before closing the body tag).
Solution 3:
If your aim is to add the class to body
immediately as the page is loaded, perhaps to hide no-JS-fallback elements, you could do that just immediately inside the body tag rather than waiting for any events:
<body><scripttype="text/javascript">document.body.className+= ' javascript';
</script>
(although in general if that's the aim it's better to remove the fallback elements as you go along replacing them with scripted elements, so that if one piece of script errors out all the other components on the page don't break.)
This is the fastest way to bind to elements: do so just immediately after creating them (inside the open tag if you only need to alter the elements; just after the close tag if you need to alter their contents). However this approach does tend to litter the page with ugly <script>
blocks, which is why more people put the code all at the bottom or use an load/ready-handler.
Solution 4:
window.onload = function() {
var elmt = document.getElementsByTagName('body');
if(elmt){
elmt[0].className = 'javascript';
}
}
That should do it.
EDIT: Updated to get element by tag name not ID.
Solution 5:
Simple:
window.onload = function() {
document.body.className = "javascript";
}
Or in HTML:
<bodyonload="document.body.className = 'javascript'">...</body>
Unless you want to differentiate between "before onload" and "after onload", you can do it statically:
<bodyclass="javascript">...</body>
Post a Comment for "How Can I Detect Dom Ready And Add A Class Without Jquery?"