Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

javascript - How can I detect DOM ready and add a class without 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'); });

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...