Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect DOM ready and add a class without jQuery?

Tags:

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'); }); 

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.

So, how would I rewrite that without jQuery?

like image 739
alex Avatar asked Nov 25 '09 06:11

alex


People also ask

How do I know if my DOM is ready?

There are two points you can have the code executed with a complete DOM tree: "load" and "DOMContentLoaded". The later is fired much earlier than the latter. Document. ready function fires as soon as the DOM is loaded and ready to be manipulated by script.

How can I implement my own $( document .ready functionality without using jQuery?

Answer: Use the DOMContentLoaded Event You can utilize the JavaScript Window's DOMContentLoaded event to construct $(document). ready() equivalent without jQuery.

How can check DOM is loaded or not in jQuery?

$(document). ready(function() { ... }); as normal – that will run the code immediately if the DOM is ready and wait until it is if not.

Which event is used to check whether DOM is loaded or not?

The DOMContentLoaded event triggers on document when the DOM is ready. We can apply JavaScript to elements at this stage. Script such as <script>... </script> or <script src="..."></script> block DOMContentLoaded, the browser waits for them to execute.


2 Answers

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();     }   }); } 
like image 108
Christian C. Salvadó Avatar answered Oct 03 '22 07:10

Christian C. Salvadó


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).

like image 25
David Hellsing Avatar answered Oct 03 '22 09:10

David Hellsing