Yes, use an <iframe> element.
You'd need to insert it in the main document, but you can hide it with display:none
and even remove it as soon as its inner document will have loaded.
Also, since the script you try to load is using document.write
, it's better we also insert our <script>
this way (some browsers will block the call from an async script).
Unfortunately, StackSnippet's null-origined iframes won't allow us to demonstrate it live here, but you can check this jsfiddle for a live demo.
function loadScript( source ) {
return new Promise( (resolve, reject) => {
const iframe = document.createElement( 'iframe' );
iframe.style = "display:none"//"opacity:0;z-index:-999;position:fixed";
iframe.src = "about:blank";
document.body.append( iframe );
const doc = iframe.contentDocument;
doc.write( `<script src="${ source }" sandbox="allow-scripts"><\/script>` );
doc.close();
iframe.contentWindow.onload = (evt) => {
iframe.remove();
resolve( doc );
};
iframe.contentWindow.onerror = (evt) => {
iframe.remove();
reject( evt );
};
} );
}
loadScript( "https://gist.github.com/ayushn21/e6f101f2e28ae609446b9aec95d4e2da.js" )
.then( doc => {
// do whatever with the Document that has loaded your script
const elem = doc.getElementById( 'gist40148058' );
console.log( elem.textContent );
} )
.catch( console.error );