正在寻找fetch js/css解决方案



我正在寻找一个解决方案,比如fetch-inject或How do I include a JavaScript file in other JavaScript file?。我真的很喜欢fetch injec,因为我可以注入多个文件,甚至css。它唯一的问题是,它不支持IE10,这对我来说是至关重要的。有什么想法,建议的解决方案吗?哦,也没有jquery。

在fetch中注入的工作方式如下:

fetchInject([
'assets/vendor/foo.js',
'assets/vendor/bar.js',
'assets/vendor/foo.css'
]).then(() => {
// after load, do something        
});

提取注入的主要代码:

const fetchInject = function (inputs, promise) {
if (!arguments.length) return Promise.reject(new ReferenceError("Failed to execute 'fetchInject': 1 argument required but only 0 present."))
if (arguments[0] && arguments[0].constructor !== Array) return Promise.reject(new TypeError("Failed to execute 'fetchInject': argument 1 must be of type 'Array'."))
if (arguments[1] && arguments[1].constructor !== Promise) return Promise.reject(new TypeError("Failed to execute 'fetchInject': argument 2 must be of type 'Promise'."))
const resources = [];
const deferreds = promise ? [].concat(promise) : [];
const thenables = [];
inputs.forEach(input => deferreds.push(
window.fetch(input).then(res => {
return [res.clone().text(), res.blob()]
}).then(promises => {
return Promise.all(promises).then(resolved => {
resources.push({ text: resolved[0], blob: resolved[1] });
})
})
));
return Promise.all(deferreds).then(() => {
resources.forEach(resource => {
thenables.push({ then: resolve => {
resource.blob.type.includes('text/css')
? head(window, document, 'style', resource, resolve)
: head(window, document, 'script', resource, resolve);
} });
});
return Promise.all(thenables)
})

};

我似乎需要添加一个不同的polyfill,它叫做whatwg fetch。它包含导致IE中出现问题的Response.clone()。如果有人想在IE10+中使用fetch-injection,请使用this和string includes polyfill。这些将涵盖所有情况。

这是一种方法。缺点是你不知道文件何时加载,好的部分是它可以在任何地方工作,并且不会干扰其他代码:

function addScript(script) {
var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
jsElement.src = script;
document.body.appendChild(jsElement);
}
function addScript("YOUR-SCRIPT-URL.js");

最新更新