How to load a stylesheet via ajax and have a callback on load

I need to load a bunch of CSS files through ajax and call the animation when the stylesheet has finished loading, otherwise the animation will fail.

What I did and got used to work well until I switched to this cross-domain is:

$.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 while resource.urlin the same domain. As soon as I try to load css from another domain $.get, the following will happen:

XMLHttpRequest cannot load https://example.com/style.css. Origin https://example.com is not allowed by Access-Control-Allow-Origin.

So, I tried adding CORS to the header via .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 affect either chrome or firefox (latest versions).

, $.getScript js , $.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.

.

? ...

+5
2

$.get Ajax, .

$.getScript Ajax, . , <script>, Same-Origin, jQuery <script> src URL script.

CSS, <link>. : 1) <link>, 2) href URL 3) load . 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 $.getCSS, .

, : URL- CSS <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 , , , .

+7

apsillers, , jQuery.

fetchStyleSheet(url, media = 'screen') {
    let $dfd = $.Deferred(),
        finish = () => $dfd.resolve(),
        $link = $(document.createElement('link'))
            .attr({
                media,
                type: 'text/css',
                rel: 'stylesheet'
            })
            .on('load', 'error', finish)
            .appendTo('head'),
        $img = $(document.createElement('img'))
            .on('error', finish); // Support browsers that don't fire events on link elements

    $link[0].href = $img[0].src = url;
    return $dfd.promise();
}

fetchStyleSheet('/url/to/my/stylesheet.css').done(() => {
    // Stuff after the sheet has loaded
});

, , img, .

, , . , finish /.

0

All Articles