How do you dynamically load a JavaScript file? With JavaScript of course!
1: function loadjsFile(filepath) {
2: try {
3: var h = document.getElementsByTagName('head').item(0);
4: var t = document.createElement('script');
5: if ('object' != typeof(t)) {
6: t = document.standardCreateElement('script');
7: }
8: t.setAttribute('src', filepath);
9: t.setAttribute('type', 'text/javascript');
10: h.appendChild(t);
11: } catch(e) { alert('Error: ' + e); }
12: }
13:
14: // ...
15: // Later in your code
16:
17: loadjsFile("MyDynamicScript.js");
In fact, dynamically loaded JavaScript is the basic concept for Bookmark Applets (a.k.a Bookmarklet)
With just a few tweaks you can make your own bookmarklet.
<a href="javascript: (function () { try { var h = document.getElementsByTagName('head').item(0); var t = document.createElement('script'); if ('object' != typeof (t)) { t = document.standardCreateElement('script'); } t.setAttribute('src', 'http://www.JustinKohnen.com/bookmarklet/BlogPostBootstrap.js'); t.setAttribute('type', 'text/javascript'); h.appendChild(t); } catch (e) { alert('Error: ' + e); } })();
">hyperlink</a>
If you are concerned about caching, you can always append a timestamp to your script reference.
<a href="javascript: (function () { try { var h = document.getElementsByTagName('head').item(0); var t = document.createElement('script'); if ('object' != typeof (t)) { t = document.standardCreateElement('script'); } t.setAttribute('src', 'http://www.JustinKohnen.com/bookmarklet/BlogPostBootstrap.js?x=' + new Date().getTime()); t.setAttribute('type', 'text/javascript'); h.appendChild(t); } catch (e) { alert('Error: ' + e); } })();
">hyperlink</a>
Here, try it. Drag this hyperlink up to your bookmark bar and click it. After a few seconds, you should see a special message from me to you.
Cheers and happy coding,
Justin
<postscript>
If you load reference JS files within Bookmarklet JavaScript you may introduce a race condition. This is why my little demo takes a second to load. I had to put a delay to allow for my reference files to download. And even still, it might not work on slower internet connections.
</postscript>