$.getScript,但对于 jQuery 中的样式表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14919894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:05:53  来源:igfitidea点击:

$.getScript, but for stylesheets in jQuery?

jquerycssloadstylesheet

提问by Lucas

Is there a $.getScriptequivalent in jQuery, but for loading stylesheets?

$.getScriptjQuery 中是否有等价物,但用于加载样式表?

回答by SoonDead

CSS is not a script, so you dont have to "execute" it in the sense of script execution.

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

Basically a <link>tag created on the fly and appended to the header should suffice, like

基本上一个动态<link>创建并附加到标题的标签就足够了,比如

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

or

或者

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.

如果你想在没有 jQuery 的情况下做到这一点。

The browser will respond to the change in the DOM and update your page layout accordingly.

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



EDIT:

编辑

I have read that old Internet Explorer has trouble with this, and you might need to do it like in answer to make it work:

我读过旧的 Internet Explorer 对此有问题,您可能需要像回答一样这样做才能使其工作:

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

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



EDIT2:

编辑2

Reading the file content and putting it inline (between <style>tags) is also a valid solution, but that way the CSS will not be cached by the browser.

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

回答by james2doyle

I have created an alternative to $.getScriptthat handles stylesheets. I called it $.getStylesheetfor obvious reasons.

我已经创建了一个$.getScript处理样式表的替代方案。出于显而易见的原因,我将其称为$.getStylesheet

It implements the $.Deferredobject, which means you can chain things like so:

它实现了$.Deferred对象,这意味着你可以像这样链接东西:

$.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');
});

Here is the little function for $.getStylesheet. It is just hosted on Github gist, so I can update it if I need to.

这是$.getStylesheet的小函数。它只是托管在 Github gist 上,所以我可以在需要时更新它。

回答by spiritwalker

you can use same method $.getScript to "download" style sheet, since $.getScript actually is just another HTTP request. but it will be a bit wired since css is not executable.

您可以使用相同的方法 $.getScript 来“下载”样式表,因为 $.getScript 实际上只是另一个 HTTP 请求。但它会有点有线,因为 css 不可执行。

回答by Willster

Here is a function that will load CSS files with a success or failure callback. I think this approach is better than the accepted answer because inserting a element into the DOM with an HREF causes an additional browser request (albeit, the request will likely come from cache, depending on response headers).

这是一个将通过成功或失败回调加载 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 as 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");
});

Here is another function that will load both CSS andjavascript files:

这是另一个将加载 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();
    });

}