通过 JavaScript 定义 CSS 规则的最佳实践
我正在加载仅在启用 JavaScript 时才需要的样式表。更重要的是,如果 JavaScript 被禁用,它就不能出现。在加载任何 javascript 库之前,我会尽快(在头部)执行此操作。 (我正在尽可能晚地加载所有脚本)。从外部加载此样式表的代码很简单,如下所示:
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);
它工作正常,但目前我的 CSS 文件包含的所有内容是:
.noscript {
display: none;
}
这并不能真正保证加载文件,所以我想只定义在 JavaScript 中动态规则。 这方面的最佳实践是什么?。对各种技术的快速扫描表明,它需要相当多的跨浏览器黑客攻击。
PS 请不要发布 jQuery 示例。这必须在没有库的情况下完成。
I'm loading a stylesheet that is only required when javascript is enabled. More to the point, it mustn't be present if JavaScript is disabled. I'm doing this as soon as possible (in the head) before any javascript libraries are loaded. (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:
.noscript {
display: none;
}
This doesn't really warrant loading a file, so I'm thinking of just defining the rule dynamically in JavaScript. What's best practice for this?. A quick scan of various techniques shows that it requires a fair bit of cross-browser hacking.
P.S. pleeease don't post jQuery examples. This must be done with no libraries.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
唔。如果节省几个字节的带宽不是问题,为什么不加载所有样式表,而是在 JavaScript 中的所有类前面加上一个特定的类:
在没有该类的情况下为正文提供服务
,并添加一个小的 JavaScript 来添加类名,例如:
为了更早地实现切换过程,您可以研究本机 Javascript onDOMLoad 解决方案之一。
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:
serve the body without that class
and add a tiny JavaScript that adds the class name, something like:
to get the switching process even more early, you could look into one of the native Javascript onDOMLoad solutions.