February 26, 2013

How to create iframe about:blank without src but content html javascript

Question by Binh Nguyen

I want to create a iframe without src ( about:blank ) but that iframe content some javascript html

I need to do it because dont want create a hosted webpages on server for this mission, this will make more connection to server which are no good for resource. And also dont want write direct javascript html on webpage because they make the webpage load slow most time when load/running.

how to do it by using javascript (jquery maybe ) to do it

iframe eg :

<iframe src="about:blank" width="300" height="250" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" ></iframe>

and its content:

<div>xxx</div>
<script type="text/javascript">var abc=1 </script>
<script type="text/javascript" src="http://1234.net/js.js"></script>

================
==========UPDATE =====

Thanks for some answered following.
But I need to clear that script will create iframe by javascript also. because need to be create iframes in one page with differ id
Please look at my test:
http://jsfiddle.net/rDkEw/

The problems are:
if use document.body.appendChild the iframe will create on body of webpage , but i need it to keep in side current div which hold the JavaScript

thanks for any help

Answer by Starx

You can do it like this:

iframe = document.getElementById('iframeid');

div_el = document.createElement('div');
div_el.innerHTML = "....";
iframe.contentWindow.docum-ent.body.appendChild(div_el);

A jQuery solution:

$('#iframeid').contents().find('body').append("<div>.....</div>");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!