Can I run a JS script from another using `fetch`?

Fetch API is supposed to provide promise-based API to fetch remote data. Loading random remote script is not AJAX – even if jQuery.ajax is capable of that. It won’t be handled by Fetch API.

Script can be appended dynamically and wrapped with a promise:

const scriptPromise = new Promise((resolve, reject) => {
  const script = document.createElement('script');
  document.body.appendChild(script);
  script.onload = resolve;
  script.onerror = reject;
  script.async = true;
  script.src="https://stackoverflow.com/questions/44803944/foo.js";
});

scriptPromise.then(() => { ... });

SystemJS is supposed to provide promise-based API for script loading and can be used as well:

System.config({
  meta: {
    '*': { format: 'global' }
  }
});

System.import("https://stackoverflow.com/questions/44803944/foo.js").then(() => { ... });

Leave a Comment

techhipbettruvabetnorabahisbahis forumuedueduseduedueduseduseduedueduedu