Skip to content

Instantly share code, notes, and snippets.

@14paxton
Last active October 7, 2022 16:47
Show Gist options
  • Save 14paxton/a5a6b17131a2791b757973f866e3eb98 to your computer and use it in GitHub Desktop.
Save 14paxton/a5a6b17131a2791b757973f866e3eb98 to your computer and use it in GitHub Desktop.
using readable stream take html file and insert it into current window document
const cdnSubstitueStrings = ["https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js",
"https://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js",
"https://s3.amazonaws.com/tb.tbex.rsrcs/lib.common/js/bootstrap-validator/dist/validator.min.js",
"https://s3.amazonaws.com/tb.tbex.rsrcs/lib.common/js/H5F/h5f.min.js",
"https://s3.amazonaws.com/tb.tbex.rsrcs/lib.common/js/tbexUtils.min.js"]
function streamHTML(pathToHTML, cssFilePath) {
fetch(pathToHTML)
.then((response) => response.body)
.then((rb) => {
const reader = rb.getReader();
return new ReadableStream({
start(controller) {
// The following function handles each data chunk
function push() {
// "done" is a Boolean and value a "Uint8Array"
reader.read().then(({done, value}) => {
// If there is no more data to read
if (done) {
controller.close();
return;
}
// Get the data and send it to the browser via the controller
controller.enqueue(value);
// Check chunks by logging to the console
push();
});
}
push();
},
});
})
.then((stream) =>
// Respond with our stream
new Response(stream, {headers: {'Content-Type': 'text/html'}}).text()
)
.then((result) => {
// const htmlDoc = document.implementation.createHTMLDocument();
// htmlDoc.body.innerHTML = result
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(result, 'text/html')
addKnownCDNScripts(htmlDoc)
addCSS(htmlDoc)
handleImages(htmlDoc)
addScriptElementsFromBody(htmlDoc)
window.document.write(htmlDoc.documentElement.outerHTML)
// window.document.body.appendChild(container.body)
window.document.close()
});
function addCSS(htmlDoc) {
const cssLink = htmlDoc.createElement('link')
cssLink.rel = "stylesheet"
cssLink.type = 'text/css'
cssLink.href = cssFilePath
htmlDoc.head.appendChild(cssLink)
}
function addKnownCDNScripts(htmlDoc) {
cdnSubstitueStrings.forEach(cdnURL => {
const cdnScript = htmlDoc.createElement('script')
// cdnScript.setAttribute('async', 'async')
cdnScript.setAttribute('type', ' text/javascript')
cdnScript.setAttribute("referrerpolicy", 'unsafe-url')
cdnScript.setAttribute('fetchpriority', 'high')
cdnScript.setAttribute('src', cdnURL);
cdnScript.setAttribute("onerror", 'console.log("script error: ' + ' src: ' + cdnScript.src + '")');
cdnScript.setAttribute("onload", 'console.log("script loaded: ' + ' src: ' + cdnScript.src + '")');
htmlDoc.head.appendChild(cdnScript)
})
}
function addScriptElementsFromBody(htmlDoc) {
const scripts = htmlDoc.querySelectorAll('script')
let userMadeScripts = []
for (let script of scripts) {
const newScript = script.cloneNode(true)
script.remove()
newScript.setAttribute("referrerpolicy", 'unsafe-url')
// newScript.crossOrigin = "anonymous";
if (!newScript.type) {
newScript.setAttribute("fetchpriority", 'high')
newScript.setAttribute("onerror", 'console.log("script error: ' + newScript.id + ', src: ' + newScript.src + '")');
newScript.setAttribute("onload", `console.log("script loaded: ")`);
console.log(newScript)
htmlDoc.body.prepend(newScript)
}
else {
newScript.setAttribute('type', ' text/javascript')
newScript.setAttribute("fetchpriority", 'auto')
userMadeScripts.push(newScript)
}
}
userMadeScripts.forEach(scriptElement => htmlDoc.body.append(scriptElement))
}
function handleImages(htmlDoc) {
const fileFolderArray = pathToHTML.split('/')
const fileURLIndex = fileFolderArray.findIndex(folderOrFile => folderOrFile.includes('html'))
const images = htmlDoc.querySelectorAll('img');
if (~fileURLIndex && images.length > 0) {
for (let image of images) {
const images = image.src.split('/');
fileFolderArray[fileURLIndex] = [...images].pop();
image.setAttribute('src', fileFolderArray.join('/'))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment