Wednesday, May 25, 2016

Set content in an iframe or load scripts in it asynchronously

Sometimes you may have to load the scripts or content inside and iframe. This will be helpful especially if you are loading an ad or video on a web page and do not want to slow down the whole web page. Given below is an example on how to load content inside an iframe asynchronously.


    <iframe id="myiframe" height="300" width="700"></iframe>
    <script>
        window.setTimeout(setIframeContent,1000);
        function setIframeContent() {
            //set content or script
            var html = '<body><div>my content</div><scr' + 'ipt>alert("test")</' + 'script></body>';
            //get reference to iframe and load the content to iframe
            var iframe = document.getElementById("myiframe");
            iframe.contentWindow.document.open();
            iframe.contentWindow.document.write(html);
            iframe.contentWindow.document.close();
           
        }

    </script>

No comments: