I need to load a bunch of CSS files through ajax and call an animation when the stylesheet has finished loading, otherwise the animation will fail.
What I have done so and used to work pretty well until I came accross doing this cross-domain is this:
$.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
});
This works fine as long as resource.url is on the same domain. Once I try to load the css from another domain $.get will fail like this:
XMLHttpRequest cannot load https://example.com/style.css. Origin https://example.com is not allowed by Access-Control-Allow-Origin.
So I have tried to add CORS into the header through .htaccess:
<IfModule mod_headers.c>
#cross domain access is okay for resources (#107)
<FilesMatch "\.(css|js)$">
Header add Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
This adds the CORS header to all CSS and JS resources.
For some reason CORS doesn't seem to have an effect on either chrome or firefox (newest versions).
I also came to notice that same domain policy is not enforced when doing $.getScript for js files, but it is for $.get:
$.get("https://example.com/script.js", {cache: false}, $.noop, "script");
//works regardless of CORS
but:
$.get("https://example.com/script.js", {cache: false}, $.noop);
//does not work (cross domain policy violation)
So since CORS is not widely supported and doesn't even seem solve the problem for a modern browser, I need something that behaves like $.getScript, but for CSS stylesheets.
It needs to be asynchronous and have a callback mechanism.
Any ideas? Thanks in advance...
foo.comis performing a fetch for a CSS resource on some other domainbar.com. You have added the CORS headers to the pages onbar.com, correct?