Explain Codes LogoExplain Codes Logo

Specifying content of an iframe instead of the src attribute to a page

javascript
prompt-engineering
functions
data-urls
Anton ShumikhinbyAnton Shumikhin·Jan 16, 2025
TLDR

Fast and furious: inline iframe content without src by leveraging srcdoc attribute:

<iframe srcdoc="<h1>Your inline content!</h1><p>src attribute? Sayonara!</p>"></iframe>

Monolith coding: Keep your HTML and iframe content in a single document, and say goodbye to external page-load stress with srcdoc. When srcdoc can't cover it, write JavaScript directly into an iframe initialized with src="about:blank".

Write into iframes using JavaScript

Scripting dynamic content

Kick off with an iframe filled with nothing but sweet, sweet white space:

<iframe id="myIframe" src="about:blank"></iframe>

Bring this blank canvas to life with a dash of JavaScript:

const iframe = document.getElementById('myIframe'); const doc = iframe.contentWindow.document; doc.open(); doc.write("<h1>Behold!</h1><p>You've created content with JavaScript.</p>"); // Like a God doc.close(); // Don't forget to close the door

Conquering advanced techniques

Create a clean slate with about:blank or manage content dynamically with JavaScript. Use data: URLs to load stuff into your iframes:

iframe.src = 'data:text/html;charset=utf-8,' + encodeURI("<h1>Isn't this splendid?</h1>");

Enjoy the power of encodeURIComponent and data: URLs to stuff the iframe like a Thanksgiving turkey.

Template-storing and Optimizations

Script a plan by sandwiching your HTML template between <script type="text/template"> tags:

<script type="text/template" id="contentTemplate"> <h1>HTML Template</h1> <p>Ready for action.</p> </script>

Slide this HTML goodness into your iframe when the time is right:

const template = document.getElementById('contentTemplate').innerHTML; iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(template); // Tastes like performance improvements

Avoid Mayhem of nested iframes: steer clear of slow loads and headaches.

Painting the big picture

When should I use srcdoc vs. data URLs?

The choice is simple: srcdoc when you've your content in a string, ready to rock 'n roll. Choose data URLs when you're dealing with dynamic content, or when you need encodeURIComponent to handle the rowdy, special characters.

Boosting performance in paint by numbers

Enhanced performance is all about smart content management. Try HTML-tag hide and seek: nestle your HTML content templates in the humble <script> tag camouflage, effectively dodging loading bottlenecks.

Handling intricate designs

With art, intricacy equals complexity. Keep the loading delays at bay caused by DOM chaos. The classic doc penmanship works well for most, but intricate designs cry out for a more refined quill: the data URLs.