0

我正在一个站点上工作,我需要检查远程主机上的 CSS 文件是否存在,然后加载同一 CSS 文件的本地副本(如果不存在)。

我正在处理的代码,

<script>
function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}
function AddLocalCss(){ document.write('<link rel="stylesheet" type="text/css"  href="css/html5-reset.min.css">') }
</script>
<script>!UrlExists('http://meyerweb.com/eric/tools/css/reset/reset.css') && AddLocalCss();</script>

但这会引发错误,(在 Chrome 开发人员工具中检查时)

XMLHttpRequest cannot load http://meyerweb.com/eric/tools/css/reset/reset.css. Origin http://example.com is not allowed by Access-Control-Allow-Origin.
Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101 

任何人都可以提出解决方案或解决方法来实现这一目标吗?

4

2 回答 2

0

you can use some of the functionality of this post: Dynamically loading css file using javascript with callback without jQuery, you can use straight that function.

I hope this would help

于 2012-08-15T15:28:42.403 回答
0

XHR is limited by Same Origin Policy - you can't request resources from another domain/protocol without jumping extra hoops. You must either request remote server to set up CORS or don't use XHR at all.

Instead of it you can just generate a link element and watch either its state or state of other elements that loaded style would affect. Unfortunately this behavior is not standartized across browsers, but, fortunately, there are some libraries to simplify dealing with it. Check out Ensure.

于 2012-08-15T15:28:51.620 回答