- <script src='some-script-file.js'></script>
- Use a library function like jQuery's $.getScript(...)
- Inject a script tag into the page using document.write(..)
- Create a script element via document.createElement('script'), fill it in with a text node and append it via document.head.appendChild(...)
First with PHP. There are a lot of ways to do it with PHP but I am going to show you how to create a script tag via a base64 'data-uri'.
echo <<<EOF <!DOCTYPE HTML> <html> <head> <meta charset='utf8'/> <!-- jQuery --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- dynamic script --> $script </head> <body> <p id='clickme' style='color: red'>ClickMe</p> <!-- More stuff goes here --> EOF;
Now if you click the red 'ClickMe' paragraph the alert fires.
You can look at the code using Firebug or Chrome tools (and I am sure there is some way to look at the code in IE -- maybe). You can also look at the code by typing CTRL-u on most browsers. Note that the actual page code is a bit more complex than what I have shown above.
Again I am using jQuery. First we create a blob. You should check somehow to see if blobs and data-uri's are supported in the browser as some OLD (read that Internet Explorer) versions of browsers don't support much HTML5 or for that matter much of anything.
The blob has pretty much the same code as used in the PHP example except we are using another paragraph element with an id of 'clickme2'.
We then create a script element. We turn the blob into a data-uri and assign the uri to the 'src' attribute of the script. We set the name attribute so it is easier to find the script in the code if you look with the debugger. Then the script is appended to the 'head' section.
Below is the green 'ClickMe2' paragraph:
// Create the text $data =<<<EOF <!DOCTYPE HTML> <html> <head> <meta charset='utf8'/> </head> <body> <h1>I am an IFRAME</h1> <p>Dynamically created iframe using PHP.</p> </body> </html> EOF; // Turn it into a data uri $data = "data:text/html;base64," . base64_encode($data);
Then in your HTML source just add the iframe as usual with the 'src' tag.
That is all there is to it.
Blobs and data-uri's are great fun. Another use for these is dynamically creating <iframe> tags. It is nice to be able to dynamically create an iframe rather than having to load it from a file somewhere. For a long time this was just not possible or very very hard to achieve. In the past I have resorted to temporary files or trickie 'eval' code. This blob-data-uri way is much nicer I think.