0

I am working on a site, where i need to check if a CSS file on a remote host exists or not and then load the local copy of the same CSS file, if it doesn't exists.

Code on which I am working,

<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>

But this throws an error, (when checked in Chrome Developer tools)

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 

Can anyone please suggest a solution or a workaround to achieve this?

Pankaj Parashar
  • 9,762
  • 6
  • 35
  • 48
  • you are not allowed to copy css from the website's servers.. – Rajat Singhal Aug 15 '12 at 15:23
  • This seems to be an XSS preveting technique. The header Access-Control-Allow-Origin should contain a reference to your domain OR `*` for everywhere. – Rolice Aug 15 '12 at 15:24
  • Possible duplicate: http://stackoverflow.com/questions/3794128/how-to-check-if-an-external-cross-domain-css-file-is-loaded-using-javascript?rq=1. Basically, you're running into a cross-domain access control policy issue. – Tim S. Van Haren Aug 15 '12 at 15:24
  • You can use this script: http://asimishaq.com/dynamically-loading-css-and-js-files – asim-ishaq Mar 12 '14 at 13:01

2 Answers2

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

Community
  • 1
  • 1
Ankur Ghelani
  • 659
  • 4
  • 16
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.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68