I'm trying to add a JavaScript file to the header of an iframe so that upon loading, the iframe can before a "background task" for me. Currently the iframe is empty, because there is no source I want it to display. Namely, all the iframe will do is perform the script I wish to supply to it.
I have tried suggestions from here:
- Can't append <script> element
- Insert a Script into a iFrame's Header, without clearing out the body of the iFrame
- Invoking JavaScript code in an iframe from the parent page
- Calling javascript function in iframe
- http://www.getallfix.com/2013/08/how-to-include-or-add-external-javascript-file-to-iframe-how-to-add-js-to-iframe/
Yet I cannot get a simple "write" to the iframe to work. Here's the code I am working with:
demo.html
<html>
<head>
<script src="demo.js"></script>
<script>
addScript('demo.js');
function addScript(src){
// Find the iFrame
var iframe = document.getElementById('test');
var val = '<scr' + 'ipt type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></scr' + 'ipt>';
var headID = iframe.getElementsByTagName("head")[0];
var newScript = iframe.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'demo.js';
headID.appendChild(newScript);
</script>
</head>
<body>
<div class="output">
<iframe id="test"></iframe>
</div>
</body>
</html>
demo.js
document.write("Hello, I'm a Demo.");