【问题标题】:How do $.get multiple css file contents?$.get 如何获取多个 css 文件内容?
【发布时间】:2018-07-11 16:31:29
【问题描述】:

我可以通过这种方式获取单个css文件的内容

getStyleCSS = $.get("MyStyle.css");
$.when(getStyleCSS).done(function(response) {
    var strCSS = response; // response here is the text content of the css file
}

但是当我尝试像这样获取几个 css 文件内容时,我得到的是 Deferred 对象而不是 css 内容。

// Get a handle on an aspx created element which contains css script elements
var elementDiv = document.getElementById('somediv');

// Get the stylesheets from this element
var links= elementDiv.getElementsByTagName('link');
arrLinks = [];
arrDeferreds = [];

// jQuery get each of the css links
for (var i = 0; i < arrLinks.length; i++) {
    var link = arrLinks[i];
    arrDeferreds.push($.get(link));
}

// Fetch the css documents
$.when(arrDeferreds).done(function (response) {
    var result = response; // response here is an array of Deferred objects
}

有没有办法使用javascript/jQuery获取多个css文件的文本内容?

上下文: 我需要将页面 HTML 的子集发送到外部(跨站点)服务,该服务将生成指定 HTML 的 PDF。为了正确生成pdf,我需要将所有css内容的文本嵌入到html中。页面内容源自 aspx/ascx 控件,其中一些控件包含指向各种 css 文件的脚本元素。我正在尝试获取每个元素的 css 文本内容。

【问题讨论】:

  • 我想你可能会在这里找到答案? stackoverflow.com/questions/1679507/…
  • 我认为你是对的,这消除了从服务器获取第二次数据的需要,所以这是双赢的。谢谢!
  • 如果您找到解决方案,请将其发布并标记为答案!欢呼
  • 它不会让我将其标记为 2 天的解决方案(不太确定为什么),但我会尽可能地这样做。再次感谢您的帮助。

标签: javascript jquery jquery-deferred


【解决方案1】:

这并不是一个真正的解决方案(我还没有弄清楚如何从 Deferred 对象中获取结果),但这似乎是一个合法的解决方法。感谢@AussieJoe 提供指向另一个stackoverflow 答案的指针。

我可以像这样为页面上的所有 css 建立 css 字符串

var strCSS = '';
for (var i = 0; i < document.styleSheets.length; i++) {
    var stylesheet = document.styleSheets[i];
    for (var j = 0; j < stylesheet.cssRules.length; j++) {
        var rule = stylesheet.cssRules[j];
        strCSS += rule.cssText;
    }
}

【讨论】:

    【解决方案2】:

    您的代码的一个问题是$.when() 不接受延迟/承诺数组作为参数。来自the jQuery doc

    如果将单个参数传递给 jQuery.when() 并且它不是 Deferred 或 Promise,它将被视为已解决的 Deferred,并且任何附加的 doneCallbacks 都将立即执行。

    所以,传递一个延迟数组,只是将数组返回给你。

    相反,它需要将它们作为单独的参数传递,并将结果作为单独的参数提供给.done(),如下所示:

    $.when(d1, d2, d3).then(function(r1, r2, r3) {
        console.log(r1, r2, r3);
    });
    

    如果您像在代码中一样在数组中包含延迟,则可以使用.apply() 传递它们。然后,结果又不是以数组的形式提供给您,而是以.done() 的一系列单独参数的形式提供给您(同样,真的很不方便)。

    因此,您可以更改此代码:

    // jQuery get each of the css links
    for (var i = 0; i < arrLinks.length; i++) {
        var link = arrLinks[i];
        arrDeferreds.push($.get(link));
    }
    
    // Fetch the css documents
    $.when(arrDeferreds).done(function (response) {
        var result = response; // response here is an array of Deferred objects
    }
    

    到这里:

    // jQuery get each of the css links
    for (var i = 0; i < arrLinks.length; i++) {
        var link = arrLinks[i];
        arrDeferreds.push($.get(link));
    }
    
    // Fetch the css documents
    $.when.apply($, arrDeferreds).done(function() {
        // copy arguments object into an actual array
        let results = Array.prototype.slice.call(arguments);
        console.log(results);
    }
    

    或者,在 ES6 中,您可以只使用使用数组的 Promise.all()

    // Fetch the css documents
    Promise.all(arrDeferreds).then(function(results) {
        console.log(results);
    });
    

    长话短说,在任何类型的现代 Javascript 环境中,请使用 Promise.all() 而不是 $.when()


    仅供参考,如果你不能使用 Promise.all() 或 polyfill,那么我不久前开发了这个 $.all() 实现,它可以让你使用数组:

    // jQuery replacement for $.when() that works like Promise.all()
    // Takes an array of promises and always returns an array of results, even if only one result
    $.all = function(promises) {
        if (!Array.isArray(promises)) {
            throw new Error("$.all() must be passed an array of promises");
        }
        return $.when.apply($, promises).done(function () {
            // if single argument was expanded into multiple arguments, then put it back into an array
            // for consistency
            var args = Array.prototype.slice.call(arguments, 0);
            if (promises.length === 1 && arguments.length > 1) {
                // put arguments into an array for consistency
                return [args];
            } else {
                return args;
            }
        });
    };
    

    【讨论】:

    • 非常感谢!我知道必须有一个聪明的方法来做到这一点。
    • @nickvans - 查看我在答案末尾添加的内容$.all()
    猜你喜欢
    • 2022-06-23
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 2022-08-10
    • 2013-04-07
    • 2013-12-23
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多