Javascript "Include"
For a project I was working on, I wanted the ability to do simple "include"-type instructions in order to spread my code across multiple JavaScript files without the necessity for a developer to manually type out <script> tags to include them all. I came across several posts which used the browser's DOM to dynamically generate and add <script" tags.
This worked fairly well ... except under Internet Explorer where it would randomly do ... nothing.
I decided that I needed more control over what was actually happening (instead of hoping the browser would see the new tag and execute it in a timely manner). As such, I switched over to using a synchronous AJAX call, as seen below:
var BrowserToolkit = { // ... code here include: function(uri) { if (!(uri in this.__included_uris)) { var xhr = BrowserToolkit.Identification.IE && BrowserToolkit.Identification.Windows ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); // perform a SYNCHRONOUS action xhr.open("GET", uri, false); xhr.send(null); if (xhr.status == 200) eval(xhr.responseText); this.__included_uris.push(uri); } } }
There's a bit of "fluff" in there, but it's obvious what it's doing. I do realise that "eval()" might possibly have some security consideration, but I think it's worth it here. This works identically in FireFox and Internet Explorer, so I've gained compatibility
Comments
There are no comments for this post.
Add comment
Visit my Friends and Family
If you've enjoyed my site, please take a moment to visit my friends and family, many of whom have some interesting insights, and entertaining thoughts and ideas.
- Crause Family - the family website
- Peter Crause - my father
- Justin Crause - my brother
- Cencina Photomagic - great photographer
- Sophistica - hair design