Last active
September 24, 2017 22:24
-
-
Save arcatdmz/e296b13dcd83967db7c73efad86cdc52 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface FileIface { | |
path: string; | |
} | |
interface FileRequest extends FileIface { | |
mode?: string; | |
element?: HTMLElement; | |
} | |
interface FileResponse extends FileIface { | |
content: string; | |
} | |
var files: { [path: string]: FileRequest } = {}; | |
var htmlDoc: HTMLDocument; | |
window.onload = function(){ | |
var html = window['template'](); | |
var parser = new DOMParser(); | |
htmlDoc = parser.parseFromString(html, 'text/html'); | |
var scripts = htmlDoc.getElementsByTagName('script'); | |
_.each(scripts, (e) => { | |
var src = e.getAttribute('src'); | |
if (typeof src !== 'string') return; | |
console.log('look for script:', src); | |
requestFile(src, 'script', e); | |
}); | |
var links = htmlDoc.getElementsByTagName('link'); | |
_.each(links, (e) => { | |
if (e.rel !== 'stylesheet') return; | |
var href = e.getAttribute('href'); | |
if (typeof href !== 'string') return; | |
console.log('look for stylesheet:', href); | |
requestFile(href, 'stylesheet', e); | |
}); | |
if (_.keys(files).length <= 0) { | |
onAllFilesReceived(); | |
} | |
} | |
// function requestFile(src, mode, el) { asyncLoad(src, mode, el).then(onFileReceived); } | |
function onFileReceived(file: FileResponse) { | |
if (!file.path || !files[file.path]) return; | |
console.log('received:', file); | |
var f = files[file.path] | |
, e = f.element; | |
if (f.mode === 'script') { | |
if (typeof file.content === 'string') { | |
e.removeAttribute('src'); | |
e.appendChild(htmlDoc.createTextNode(file.content)); | |
} | |
} else if (f.mode === 'stylesheet') { | |
var style = htmlDoc.createElement('style'); | |
style.setAttribute('type', 'text/css'); | |
style.appendChild(document.createTextNode(file.content)); | |
e.parentElement.replaceChild(style, e); | |
} | |
delete files[file.path]; | |
if (_.keys(files).length <= 0) { | |
onAllFilesReceived(); | |
} | |
} | |
function onAllFilesReceived() { | |
document.open(); | |
document.write(htmlDoc.documentElement.outerHTML); | |
document.close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment