4 ways to dynamically load external JavaScript(with source)

February 10th, 2008 Ntt.cc

Most of the time, Firefox, Safari and Opera work without much effort and differences between the 3. However, throw IE into the mix and you’re in a whole different world.This is helpful if you need to dynamically inject javascript.And, the biggest problem was setting a function that you want executed after the script is loaded.By this article I will provide 4 way to dynamically load external JavaScript.

The below 1,2,3 are asynchronous,only 4 is synchronization.

choice 1. Using document.write

// you need to put an escape character before the closing </script> tag, like this: <\/script>
<script language="javascript">
document.write("<script src='other.js'><\/script>");
</script>

Of course, there are some problems with injecting JS code and you also potentially have a cross-domain issue.At this time,the preferred way of injecting JS code seems to be to use AJAX to load the JS source, then eval() the code.

[...] ways to dynamically load external JavaScript(with source) This entry was written by minidxer. Bookmark the permalink. Follow any comments here with the RSS feed for this post.Content related [...]

I spent over 2 hours trying to find a solution for Internet Explorer 6′s inability to load an external javascript. My external script worked fine in Mozilla and Firefox but came up shooting blanks with IE6. It was driving me crazy. In the end I decided to “Dynamically change the src property value.” It worked like a charm. I’m going to print out all four ways and keep them handy just in case.

You may want to look at Ajile [ http://ajile.iskitz.com/ ]. It provides a Load() function for dynamically loading external and/or raw JavaScript code.

Ajile is cross-browser and can dynamically load external JavaScript before or after a page has loaded. Ajile is is also capable of loading local (i.e. file//…) and cross-domain scripts unlike the XMLHttpRequest method shown in approach #4.

Nice to see this message after fighting with IE7 for 2 hours. I’ve finally solved my problem by choice 2 but I need the script be loaded in synchronized state. The choice 4 seems to be the best way to solve me problem, but what if the dynamically loaded script is exactly the AJAX library itself? Any sugesstion to “bootstrap” a external AJAX script?

With SidJS you can load both scripts and stylesheets on demand. jQuery’s getScript() (or any other AJAX solution) can’t do cross-domain requests. As a bonus, SidJS also loads stylesheets and executes a callback function when they’re done (even in Firefox, a browser that doesn’t support neither load nor readystatechange events on link tags)

Trying to load my external js fle with wordpress into the header of the page, but wp_enqueue_script and admin_enqueue_script are printing the content of the page to the header of the page instead to add a link to the external javascript file – anybody has a solution ? please help