In a web extension, I've been passing template elements from the background page as strings to an empty local HTML file and using browser.tabs.insertCSS
and browser.tabs.executeScript
to pass CSS and JS. That has been working well but I recently learned that fetch can be used to retrieve the files from the extension directly, which would reduce the size of the background page or eliminate it altogether, leaving just the background script and reducing RAM usage.
I've seen some examples in this SO question that write the HTML string to the body element using innerHTML
and one that uses a DOMParser.
But if you try it, the HTML is added to the body element.
Another SO question, ten years old, had a five-year-old last response that was interesting, to a novice like me anyway; and I tried this, which appears to work.
fetch('file.html')
.then( response => response.text() )
.then( result => {
let parser = new DOMParser(),
doc = parser.parseFromString( result, 'text/html' );
document.replaceChild( doc.documentElement, document.documentElement );
} );
My question is, is this a valid and reliable method of replacing the html element completely?
Thank you.