levipadre
levipadre

Reputation: 619

Looking for a fetch js/css solution

I'm looking for a solution like fetch-inject or How do I include a JavaScript file in another JavaScript file?. I really like fetch-injec, because I can inject multiple files, even css. The only problem with it, that it doesn't support IE10 which is crucial for me unfortunately. Any ideas, suggested solutions? Oh, and no jquery too.

In fetch-inject works like this:

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

The main code of fetch-inject:

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)
})

};

Upvotes: 1

Views: 1179

Answers (2)

levipadre
levipadre

Reputation: 619

It seems I needed to add a different polyfill, it called whatwg-fetch. It contains Response.clone() which caused the problem in IE. If anybody wants to use fetch-inject in IE10+, use this and string-includes-polyfill too. These will cover every cases.

Upvotes: 2

alotropico
alotropico

Reputation: 1994

This is one way to do it. The drawback is that you don't know when the file is loaded, the good part is that it works everywhere and it doesn't interfere with other code:

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");

Upvotes: 1

Related Questions