Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Safe AND quickest way to add a css class to the body of the DOM

I am looking to add a class to the body element of the DOM. For something so simple, and with the body element itself loading quick (at least, I would think it would load quicker than, say, an element buried deem in the DOM), must I really wait for the jQuery Ready event to do such a simple task? I'm looking to avoid a "flicker" effect when adding the style to the body, since I'll have different CSS styles attached to this class take effect when added.

I can do something like:

  jQuery(window.document).ready(function () {
    jQuery("body").addClass("home");
  });

But is there a faster, yet safe way? I don't care if its jQuery or native JavaScript

question from:https://stackoverflow.com/questions/17457583/safe-and-quickest-way-to-add-a-css-class-to-the-body-of-the-dom

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

1 Reply

0 votes
by (71.8m points)
document.body.className += ' home';

Performance comparision: className vs classList vs addClass :

Update(based on PSL's comment)

or for newer ones document.body.classList.add("home");

Make sure you do this under the <body>, it won't work if applied from a <head> script


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...