Skip to content

Instantly share code, notes, and snippets.

@jtrein
Last active March 21, 2017 10:09
Show Gist options
  • Save jtrein/388b92a25301d8fd665a5dbf66ccdb86 to your computer and use it in GitHub Desktop.
Save jtrein/388b92a25301d8fd665a5dbf66ccdb86 to your computer and use it in GitHub Desktop.
Load Scripts and HTML from a Fetched Web Page (load scripts from another webpage)
/**
* Load HTML + scripts from a fetched HTML page (e.g. fetch a GitHub project page)
*
* PS - not really thatttttt useful. If you're using this, it's probably because
* of a bad design choice, initially. I just wanted a mini-challenge.
*/
fetch('[URL_OF_WEBPAGE]')
.then((res) => res.text())
.then((text) => {
this.apiRoot.innerHTML += text;
return this.apiRoot;
})
.then((placeholder) => {
const createScriptTag = (src, text) => {
const scriptEl = document.createElement('script');
if (src === undefined || src === null) {
scriptEl.innerHTML += text;
return scriptEl;
}
scriptEl.src = src;
return scriptEl;
};
const appendScriptTag = (el) => document.body.appendChild(el);
const scripts = placeholder.getElementsByTagName('script');
const promises = [];
for (let i = 0; i < scripts.length; i += 1) {
const src = scripts[i].getAttribute('src');
const promiseLoadScript = () => (
new Promise((resolve) => {
const appended = appendScriptTag(
createScriptTag(src, scripts[i].innerHTML)
);
if (appended.src === '' || src === null) return resolve();
return (appended.onload = resolve);
})
);
promises.push(promiseLoadScript);
}
function series(list) {
const p = Promise.resolve();
return list.reduce((pacc, fn) => {
const newPromise = pacc.then(fn);
return newPromise;
}, p);
}
series(promises);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment