$.getScript, but for stylesheets in jQuery?

有一个$.getScriptjQuery等等效,但用于装载样式表?

适用::stackoverflow.com/a/3994218/350858Sudhir Bastakoti
You can easily load and inject CSS, but firing a callback when the CSS has been loaded AND applied to the DOM is close to impossible. You might need to setup a test element, make the CSS apply some styles, then test using interval when that element has the styles applies by the CSS.David Hellsing

回答 4

  1. 赞同 45

    CSS不是脚本,因此您不必在脚本执行的意义上“执行”它。

    基本A.<link>在飞行中创建的标签并附上标题应该足够,就像

    $('<link/>', {
       rel: 'stylesheet',
       type: 'text/css',
       href: 'path_to_the.css'
    }).appendTo('head');
    

    var linkElem = document.createElement('link');
    document.getElementsByTagName('head')[0].appendChild(linkElem);
    linkElem.rel = 'stylesheet';
    linkElem.type = 'text/css';
    linkElem.href = 'path_to_the.css';
    

    if you want to do it without jQuery.

    浏览器将响应DOM的更改,并相应更新页面布局。


    EDIT.:

    我已经阅读了旧的Internet Explorer对此有问题,您可能需要这样做,以便使其工作:

    https://stackoverflow.com//2685639/618206


    EDIT2.:

    read文件内容并将其插入内联(之间<style>标签也是一个有效的解决方案,但这种方式也不会被浏览器缓存的CSS。

    Vinczemarton
    这不是一个等价物,因为当CSS是“准备好”时没有回调。David Hellsing
    That is true. If you want to get a callback, you can use getScript, and insert the contents inline.Vinczemarton
    that is an option, but it’s still not reliable (depending on usage). Even if you know that the CSS file has loaded it doesn’t mean that it’s styles has been applied to the DOM.David Hellsing
    佩莱,即使是getscript也不保证在脚本执行后将调用回调。以供参考:api.jquery.com/jquery.getScript.我不确定您是否有任何方法可以判断是否已应用风格。Vinczemarton
  2. 赞同 6

    I have created an alternative to $.getScript that handles stylesheets. I called it $。GetStylesheet对于明显的原因。

    It implements the $.DeferredObject,这意味着您可以将这样的方式链断:

    $.when($.getStylesheet('css/main.css'), $.getScript('js/main.js'))
    .then(function () {
      console.log('the css and js loaded successfully and are both ready');
    }, function () {
      console.log('an error occurred somewhere');
    });
    

    小功能$。getStylesheet.它刚刚托管GitHub Gist,所以如果我需要,我可以更新它。

    James2doyle
    Adding A.<link>在DOM接近瞬间。为什么将它包装在延期?Vinczemarton
    @ SOONCEAD它是模拟相同的API。没有$.Deferred You could not use $.when at all.James2doyle
    I still don't get why would you want to wrap it in a when. You are actually better off moving the $.getStylesheet在何时并获得完全相同的结果之前。之后,您可以采取其他步骤将其从延迟释放并仍然得到完全相同的结果。Vinczemarton
    @ Soondead首先,你不必使用when,这只是您想要使用此技术的原因。假设您希望向2个脚本和2表提出请求,并且您希望等到所有完成,然后做其他事情。这是一种以干净和简洁的方式做到这一点的方法。James2doyle
    do注意,当“完成所有已完成”时,您不会完成延迟。当链接标记添加到DOM时,您完成了延迟。这不保证任何要做的事情。Vinczemarton
  3. 赞同 2

    您可以使用相同的方法$ .getscript到“下载”样式表,因为$ .getScript实际上只是另一个HTTP请求。但由于CSS不可执行,因此它将有点连续。

    PiritWalker
  4. 赞同 1

    它是一个函数,它将加载成功或失败回调的CSS文件。我认为这种方法比接受的答案更好,因为用HREF将元素插入DOM导致额外的浏览器请求(虽然,请求可能来自缓存,具体取决于响应标题)。

    function loadCssFiles(urls, successCallback, failureCallback) {
    
        $.when.apply($,
            $.map(urls, function(url) {
                return $.get(url, function(css) {
                    $("<style>" + css + "</style>").appendTo("head");
                });
            })
        ).then(function() {
            if (typeof successCallback === 'function') successCallback();
        }).fail(function() {
            if (typeof failureCallback === 'function') failureCallback();
        });
    
    }
    

    usage so:

    loadCssFiles(["https://test.com/style1.css", "https://test.com/style2.css",],
        function() {
        alert("All resources loaded");
    }, function() {
        alert("One or more resources failed to load");
    });
    

    另一个函数将加载两个CSSjavascript文件:

    function loadJavascriptAndCssFiles(urls, successCallback, failureCallback) {
    
        $.when.apply($,
            $.map(urls, function(url) {
                if(url.endsWith(".css")) {
                    return $.get(url, function(css) {
                        $("<style>" + css + "</style>").appendTo("head");
                    });
                } else {
                    return $.getScript(url);
                }
            })
        ).then(function() {
            if (typeof successCallback === 'function') successCallback();
        }).fail(function() {
            if (typeof failureCallback === 'function') failureCallback();
        });
    
    }