问题
My recent project is to try and make document.write async , of course this is almost impossible task , many have tried but i can't find any good solution and other than that i would rather try on my own. hooking document.write is quite simple :
var oldDocWrite = document.write;
document.write = function( content ) {
let domparser = new DOMParser().parseFromString(content, 'text/html'),
fragBody = document.createDocumentFragment(),
fragHead = document.createDocumentFragment(),
childNodesBody = DomParser.body.childNodes,
childNodesHead = DomParser.head.childNodes;
while (childNodesBody.length) {
//append nodes to the iframe
};
while (childNodesHead.length) {
//append nodes to the iframe
};
My goal with this code is quite simple , i'm taking the raw html parsing it with domparser api than i'm creating 2 documentfragments , one for the head tag and second for the body tag than i'm starting to append the nodes to some iframe via appendChild. Just a quick notes for the ones who unfamiliar with those apis: 1.documentfragment is decreasing on each appendChild so both of those while loops will stop when all of the nodes in the fragment are appended to the iframe. 2.the DOMParser api will add "no execute" for any script tags (look at the specs) so i'm actually breaking on each script tag and creating a new one instead.
So when the html code is simple everything is working great but when the html code is more complex i'm unable to render the html properly for several reasons: 1.another iframe is inside the html and i will need to hook the document.write in that iframe contentWindow as well. 2.eventlisteners will not fire properly. 3.another document.write call (nested one) so i need to stop appending the first one handle the second/third/... and close the recursive operations (this was extremely hard but i'm almost there) you can check this very useful link:
So long story short my worst problem is the ability to parse the raw html into nodes and appending the nodes in the correct order but also append each node at a time , in my example if some nodes have childrens than i'm actually appending the node with all of its childrens and thats will not work properly because i need to add eventlistener to script tags so i can resume appending when the script tag finished executing and also hook more nested iframes if present and i need to first append the iframe than hook its contentWindow so i will need to append each node separately and if the node have childrens than append each children separately and if this children have another one than ......
So any nice way to do that? the DOMParser api is quite complex because of its many problems (like disabling js) , i thought maybe via regex but thats seems more complicated.
来源:https://stackoverflow.com/questions/51842531/making-document-write-async