A little hack to test isolated HTML template previewing within a <iframe> using Blob - without need for another server request.
Created
January 10, 2020 09:32
-
-
Save pointofpresence/e956af2028028c4287f0bcb52062a116 to your computer and use it in GitHub Desktop.
HTML Blob in <iframe>
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
<iframe id="blob-src-test" frameborder="0" width="300px" height="300px"></iframe> | |
<iframe id="document-write-test" frameborder="0" width="300px" height="300px"></iframe> |
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
var variables = { | |
title: 'Hello', | |
image: 'https://4.bp.blogspot.com/-j49xTVdZe7g/TVnmq6phXxI/AAAAAAAABpA/Pm45FErBfQQ/s1600/hopkins%2Bduck.jpg' | |
}; | |
var template = [ | |
'<h1>', | |
variables.title, | |
'</h1>', | |
'<img width="80%" src="', | |
variables.image, | |
'">' | |
].join(''); | |
// Alt 1: Blob approach | |
var blob = new Blob([template], {type: "text/html"}); | |
var blob_url = URL.createObjectURL(blob); | |
var blob_iframe = document.querySelector('#blob-src-test'); | |
blob_iframe.src = blob_url; | |
// Alt. 2: Document write ("old school") | |
var doc = document.querySelector('#document-write-test').contentWindow.document; | |
doc.open(); | |
doc.write(template); | |
doc.close(); |
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
iframe { | |
margin: 10px; | |
} | |
#blob-src-test { | |
outline: 2px solid cyan; | |
} | |
#document-write-test { | |
outline: 2px solid magenta; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment