我需要通过 ajax 加载一堆 CSS 文件,并在样式表加载完成时调用动画,否则动画会失败。
在我遇到这个跨域之前,我已经这样做并且曾经工作得很好是这样的:
$.get(resource.url, {cache:true}, function(css) {
//Now that the stylesheet is in the browser cache, it will load instantly:
$("head").append($("<link>",{
rel: "stylesheet",
type: "text/css",
href: resource.url
}));
}).then(function(){
//Animation here that depends on the loaded css
});
只要 resource.url
在同一个域中,这就可以正常工作。一旦我尝试从另一个域加载 css,$.get
将像这样失败:
XMLHttpRequest cannot load https://example.com/style.css. Origin https://example.com is not allowed by Access-Control-Allow-Origin.
所以我尝试通过 .htaccess
将 CORS 添加到 header 中:
<IfModule mod_headers.c>
#cross domain access is okay for resources (#107)
<FilesMatch "\.(css|js)$">
Header add Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
这会将 CORS header 添加到所有 CSS 和 JS 资源。
出于某种原因CORS似乎对 chrome 或 firefox(最新版本)没有影响。
我还注意到,在对 js 文件执行 $.getScript
时,不会强制执行相同的域策略,但它适用于 $.get
:
$.get("https://example.com/script.js", {cache: false}, $.noop, "script");
//works regardless of CORS
但是:
$.get("https://example.com/script.js", {cache: false}, $.noop);
//does not work (cross domain policy violation)
因此,由于 CORS 没有得到广泛支持,甚至似乎无法解决现代浏览器的问题,我需要一些行为类似于 $.getScript
的东西,但用于 CSS 样式表。
需要异步,有回调机制。
有什么想法吗?提前致谢...
最佳答案
$.get
使用 Ajax,它必须遵守同源策略。
$.getScript
通常使用Ajax,但是它还有一个仅供跨域使用的回退选项。通过 <script>
导入的脚本标签不受同源规则的约束,所以 jQuery 只是添加了一个 <script>
标记到页面并设置其 src
请求脚本 URL 的属性。
对于通过 <link>
加载的 CSS 资源也进行了相同的豁免。标签。在一个完美的世界中,您应该能够 1) 制作一个新的 <link>
元素,2) 设置其 href
属性到正确的 URL 和 3) 监听 load
该元素上的事件。我已经向 this solution 添加了回调来自 jQuery 论坛:
// note: non-compatible example code, see below for better code
jQuery.getCSS = function( url, media, callback ) {
jQuery( document.createElement('link') ).attr({
href: url,
media: media || 'screen',
type: 'text/css',
rel: 'stylesheet'
}).appendTo('head')
.on("load", callback);
};
这里有一个小问题:它不能跨浏览器工作。 <link>
标签不触发 load
所有浏览器中的事件——参见 jQuery bug report 对于 $.getCSS
本来可以的功能。
所以,一般情况workaround is a bit insane : 添加 CSS URL 作为新 <img>
的来源标记并收听其 onerror
处理程序:
// correct code!
jQuery.getCSS = function( url, media, callback ) {
jQuery( document.createElement('link') ).attr({
href: url,
media: media || 'screen',
type: 'text/css',
rel: 'stylesheet'
}).appendTo('head');
jQuery( document.createElement('img') ).attr('src', url)
.on("error", callback);
};
您还可以添加一些优化并监听 load
<link>
上的事件(对于支持它的浏览器)和 error
<img>
上的事件(对于那些不这样做的人),并放置一些逻辑以确保回调只被调用一次,以防两个事件都发生。
至于制作$.getCSS
返回一个延迟的对象,这有点超出我的专业领域,但没有理论上的理由说明为什么它不能完成。
关于javascript - 如何通过 ajax 加载样式表并在加载完成后进行回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11444578/