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?

4
  • you are not allowed to copy css from the website's servers.. Commented Aug 15, 2012 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. Commented Aug 15, 2012 at 15:24
  • Possible duplicate: stackoverflow.com/questions/3794128/…. Basically, you're running into a cross-domain access control policy issue. Commented Aug 15, 2012 at 15:24
  • You can use this script: asimishaq.com/dynamically-loading-css-and-js-files Commented Mar 12, 2014 at 13:01

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.