简体   繁体   English

通过JavaScript定义CSS规则的最佳做法

[英]Best practice for defining CSS rules via JavaScript

I'm loading a stylesheet that is only required when javascript is enabled. 我正在加载仅在启用javascript时才需要的样式表。 More to the point, it mustn't be present if JavaScript is disabled. 更重要的是,如果禁用了JavaScript,则不得存在。 I'm doing this as soon as possible (in the head) before any javascript libraries are loaded. 在加载任何JavaScript库之前,我会尽快(在头部)执行此操作。 (I'm loading all scripts as late as possible). (我要尽可能晚地加载所有脚本)。 The code for loading this stylesheet externally is simple, and looks like this: 从外部加载此样式表的代码很简单,如下所示:

var el = document.createElement('link');
el.setAttribute('href','/css/noscript.css');
el.setAttribute('rel','stylesheet');
el.setAttribute('type','text/css');
document.documentElement.firstChild.appendChild(el);

It's working fine, but all my CSS file contains at the moment is this: 一切正常,但是我目前所有的CSS文件都是这样的:

.noscript {
    display: none;
}

This doesn't really warrant loading a file, so I'm thinking of just defining the rule dynamically in JavaScript. 这实际上并不能保证加载文件,因此我正在考虑仅在JavaScript中动态定义规则。 What's best practice for this? 最佳做法是什么? . A quick scan of various techniques shows that it requires a fair bit of cross-browser hacking. 快速浏览各种技术表明,它需要相当多的跨浏览器黑客。

PS pleeease don't post jQuery examples. PS请不要发布jQuery示例。 This must be done with no libraries. 这必须在没有库的情况下完成。

Hmm. If saving a few bytes of bandwidth is not an issue, why not load all stylesheets, but prefix all classes in the JavaScript one with a specific class: 如果节省几个字节的带宽不是问题,为什么不加载所有样式表,而是在JavaScript中的所有类前面加上特定的类:

body.hasjs a { color: blue }
body.hasjs div.contactform { width: xyz; }

serve the body without that class 没有那个阶级就为身体服务

<body>

and add a tiny JavaScript that adds the class name, something like: 并添加一个微型JavaScript,以添加类名称,例如:

body.onload = function() {
document.body.className = "hasjs"; 
}

to get the switching process even more early, you could look into one of the native Javascript onDOMLoad solutions. 为了更早地完成切换过程,您可以研究一种本机Javascript onDOMLoad解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM