如何确保 JQuery 正确动态注入 CSS 并可供使用?
我知道我可以这样做来注入 CSS,如下所示:
$(document).ready(function() {
$("a").click(function() {
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
});
});
但是,这个 async.即使我附加了链接,也不能保证 CSS 当时可用。 (因为CSS下载) 所以,如果有另一个js同时运行并尝试aasign一个类,那么 1)它仍然有效吗?文件完全下载后是否会应用CSS?
如果没有,是否有类似回调或一些技巧可以用来知道 CSS 是否已完全下载?
I know that I can do this to inject CSS like this:
$(document).ready(function() {
$("a").click(function() {
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
});
});
But, this async. i.e. even I append the link, there is no guarantee that the css is available at that time. (because of the CSS download)
so, if there is another js runs at the same time and try to aasign a class, then
1) Will it still work? Will the css applied later on after the file is fully downloaded?
If not, is there something like a call back or some trick that I can use to know that the css is fully downloaded?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你需要保证加载并且CSS肯定在同一个域上,你可以通过Ajax请求内容,然后直接注入属性。
通过在
中创建一个虚拟
元素并调用
text( )
以及 CSS 文件的内容(作为字符串)。例如,粗略地说:
但老实说,这是一个罕见的用例。
If you need it guaranteed to be loaded and the CSS is definitely on the same domain, you could request the contents via Ajax and then inject the properties directly.
I've had good luck doing this (in iOS at least) by creating a dummy
<link>
element in the<head>
and callingtext()
on it with the contents of the CSS file (as a string).For example, roughly:
But honestly this is a rare use case.