What is srcdoc in iframe: Definition and Usage
srcdoc attribute in an iframe lets you embed HTML content directly inside the iframe without loading an external page. It works like a mini webpage inside the iframe, defined right in your HTML code.How It Works
Think of an iframe as a small window on your webpage that shows another webpage. Normally, this window loads content from a separate URL using the src attribute. But with srcdoc, you can write the content directly inside the iframe tag itself.
This is like writing a tiny webpage inside a box on your page, instead of pointing to a different website. The browser reads the HTML code you put in srcdoc and displays it inside the iframe window.
This makes it easy to show simple or custom content without needing another file or server request. It’s like having a mini webpage inside your main page.
Example
This example shows an iframe with a red background and some text, all defined inside the srcdoc attribute.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>srcdoc Example</title> </head> <body> <iframe srcdoc="<p style='color: white; background-color: red; padding: 10px;'>Hello from srcdoc iframe!</p>" width="300" height="100" title="srcdoc iframe example"></iframe> </body> </html>
When to Use
Use srcdoc when you want to embed small HTML content inside an iframe without loading an external page. This is useful for showing simple messages, previews, or custom HTML snippets quickly.
It helps avoid extra server requests and keeps everything in one file, which is great for demos, testing, or embedding trusted content you control.
However, for large or dynamic content, or content from other websites, using src with a URL is better.
Key Points
- srcdoc lets you write HTML directly inside an iframe.
- It avoids loading external pages, reducing server requests.
- Good for small, static, or trusted content.
- Not suitable for large or dynamic content.
- Works in modern browsers supporting HTML5.
Key Takeaways
srcdoc embeds HTML content directly inside an iframe without external URLs.srcdoc reduces server requests and simplifies embedding trusted content.src attribute with a URL instead.srcdoc is supported in all modern browsers that support HTML5.