44

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

4

2 回答 2

116
document.body.className += ' home';

性能比较classNamevsclassListvsaddClass

更新(基于 PSL 的评论)

或较新的document.body.classList.add("home");

确保在 下执行此操作,如果从脚本<body>应用,它将不起作用<head>

于 2013-07-03T20:35:20.420 回答
3

在开始body标签之后,您可以创建一个脚本标签:

<body>
<script>
    $('body').addClass('home')
</script>
<!-- HTML content bellow -->
</body>

唯一的条件是 jQuery 被加载到head.

于 2013-07-03T20:34:10.613 回答