如何使用 jQuery 异步加载 CSS?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5186638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to asynchronously load CSS using jQuery?
提问by Adam Lukaszczyk
I want to use jQuery to asynchronously load CSS for a document.
我想使用 jQuery 异步加载文档的 CSS。
I found this sample, but this doesn't seem to work in IE:
我找到了这个示例,但这在 IE 中似乎不起作用:
<script type="text/javascript" src="/inc/body/jquery/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(function(){
$('<link>', {
rel: 'stylesheet',
type: 'text/css',
href: '/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css'
}).appendTo('head');
$.getScript("/inc/body/jquery/js/jquery-ui-1.8.10.custom.min.js", function(){
});
});
</script>
Basically I want to load jQuery UI
after the all other data, images, styles, etc load to the page.
基本上我想jQuery UI
在所有其他数据、图像、样式等加载到页面后加载。
The $.getScript
works great for JS file. Only problem is with CSS in IE.
在$.getScript
对JS文件的伟大工程。唯一的问题是 IE 中的 CSS。
Do you know a better solution?
你知道更好的解决方案吗?
采纳答案by Peter Olson
This should work in IE:
这应该适用于 IE:
$("head").append("<link rel='stylesheet' type='text/css' href='/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css' />");
回答by Dmitry Pashkevich
Here's a method for asynchronousstylesheet loading that doesn't block page renderthat worked for me:
这是一种异步样式表加载方法,它不会阻止对我有用的页面渲染:
https://github.com/filamentgroup/loadCSS/blob/master/loadCSS.js
https://github.com/filamentgroup/loadCSS/blob/master/loadCSS.js
Reduced example of the code linked above, based on lonesomeday's answer
上面链接的代码的简化示例,基于lonesomeday的答案
var stylesheet = document.createElement('link');
stylesheet.href = '/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css';
stylesheet.rel = 'stylesheet';
stylesheet.type = 'text/css';
// temporarily set media to something inapplicable to ensure it'll fetch without blocking render
stylesheet.media = 'only x';
// set the media back when the stylesheet loads
stylesheet.onload = function() {stylesheet.media = 'all'}
document.getElementsByTagName('head')[0].appendChild(stylesheet);
回答by lonesomeday
The safe way is the old way...
安全的方式是旧的方式......
var stylesheet = document.createElement('link');
stylesheet.href = '/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css';
stylesheet.rel = 'stylesheet';
stylesheet.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(stylesheet);
回答by Hendy Irawan
As mentioned in RequireJS docs, the tricky part lies notin loading the CSS:
正如RequireJS docs 中提到的,棘手的部分不在于加载 CSS:
function loadCss(url) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
but in knowing when/whether the CSS has loaded successfully, as in your use case " I want to load jQuery UI afterthe all other data, images, styles, etc load".
但是要知道 CSS 何时/是否成功加载,如在您的用例中“我想在所有其他数据、图像、样式等加载后加载 jQuery UI ”。
Ideally RequireJS could load CSS files as dependencies. However, there are issues knowing when a CSS file has been loaded, particularly in Gecko/Firefox when the file is loaded from another domain. Some history can be found in this Dojo ticket.
Knowing when the file is loaded is important because you may only want to grab the dimensions of a DOM element once the style sheet has loaded.
Some people have implemented an approach where they look for a well known style to be applied to a specific HTML element to know if a style sheet is loaded. Due to the specificity of that solution, it is not something that would fit will with RequireJS. Knowing when the link element has loaded the referenced file would be the most robust solution.
Since knowing when the file has loaded is not reliable, it does not make sense to explicitly support CSS files in RequireJS loading, since it will lead to bug reports due to browser behavior.
理想情况下 RequireJS 可以加载 CSS 文件作为依赖项。但是,知道何时加载 CSS 文件存在问题,尤其是在 Gecko/Firefox 中,当文件从另一个域加载时。在这张道场门票中可以找到一些历史。
知道文件何时加载很重要,因为您可能只想在样式表加载后获取 DOM 元素的尺寸。
有些人已经实现了一种方法,他们寻找一个众所周知的样式来应用于特定的 HTML 元素,以了解是否加载了样式表。由于该解决方案的特殊性,它不适合 RequireJS。知道链接元素何时加载了引用的文件将是最可靠的解决方案。
由于知道文件何时加载是不可靠的,因此在 RequireJS 加载中明确支持 CSS 文件是没有意义的,因为它会因浏览器行为而导致错误报告。
回答by ekerner
As per Dynamically loading css stylesheet doesn't work on IE:
You need to set the href attr last and only after the link elem is appended to the head.
您需要最后设置 href attr 并且仅在链接 elem 附加到头部之后。
$("<link>")
.appendTo('head')
.attr({type : 'text/css', rel : 'stylesheet'})
.attr('href', '/css/your_css_file.css');
回答by noamtcohen
$.get("path.to.css",function(data){
$("head").append("<style>"+data+"</style>");
});
回答by Alan H.
None of the solutions here actually load the CSS file without blocking page render - which is typically what is meant by “asynchronously.”?(If the browser is waiting for something and preventing the user from interacting with the page, the situation is by definition synchronous.)
这里没有一个解决方案在不阻塞页面渲染的情况下实际加载 CSS 文件 - 这通常是“异步”的意思。?(如果浏览器正在等待某事并阻止用户与页面交互,则情况是同步。)
Examples of synchronous and asynchronous loading can be found here:
可以在此处找到同步和异步加载的示例:
I have found that using a setTimeout
to defer loading seems to help.
我发现使用 asetTimeout
来延迟加载似乎有帮助。
回答by Praveen Prasad
jQuery(function(){
jQuery('head').append('<link href="/inc/body/jquery/css/start/jquery-ui-1.8.10.custom.css" rel="stylesheet" type="text/css" />')
});