javascript - 将 css 类添加到 DOM 主体的安全且最快的方法

标签 javascript jquery

我希望将一个类添加到 DOM 的 body 元素。对于如此简单的事情,并且 body 元素本身加载速度很快(至少,我认为它加载速度比 DOM 中埋藏的元素更快),我真的必须等待 jQuery Ready 事件来执行这样的操作吗?简单的任务?我希望在将样式添加到正文时避免“闪烁”效果,因为我将附加到此类的不同 CSS 样式在添加时生效。

我可以这样做:

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

但是有没有更快、更安全的方法呢?我不在乎它是 jQuery 还是原生 JavaScript

最佳答案

document.body.className += ' home';

Performance comparision : className对比classList对比addClass :

更新(根据 PSL 的评论)

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

关于javascript - 将 css 类添加到 DOM 主体的安全且最快的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17457583/

相关文章:

jquery - 我该如何编写这个 jQuery 函数,使其干净高效?

javascript - ajax调用后更新数据属性

javascript - 无法绑定(bind)到 'mdMenuTriggerFor',因为它不是 'button' 的已知属性

javascript - 如何为所有 Azure Application Insight 请求添加自定义属性 (JavaScript)

PHP 不发送 AJAX 调用的响应文本

javascript - 需要使用 jqueryui Accordion ,但它已被第二个库重新定义

jquery - 为什么 JQuery Mobile 在提交表单时给出 "error loading page"?

javascript - Delphi 执行命令问题,图片相关链接

javascript - 具有多种背景颜色的 Jquery Slider

javascript - 如何更改/删除兄弟方法