4 ways to dynamically load external JavaScript(with source)

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>

choice 2.Dynamically change the src property value

<script src='' id="s1"></script>
<script language="javascript">
s1.src="other.js"
</script>

choice 3.Dynamically create <script> element

<script>
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript= document.createElement("script");
oScript.type = "text/javascript";
oScript.src="other.js";
oHead.appendChild( oScript);
</script>

choice 4. Get JavaScript by using XMLHTTP,then create script object

<script language="JavaScript">
function GetHttpRequest()
{
if ( window.XMLHttpRequest ) // Gecko
return new XMLHttpRequest() ;
else if ( window.ActiveXObject ) // IE
return new ActiveXObject("MsXml2.XmlHttp") ;
}
function AjaxPage(sId, url){
var oXmlHttp = GetHttpRequest() ;
oXmlHttp.OnReadyStateChange = function()
{
if ( oXmlHttp.readyState == 4 )
{
if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 )
{
IncludeJS( sId, url, oXmlHttp.responseText );
}
else
{
alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ;
}
}
}
oXmlHttp.open('GET', url, true);
oXmlHttp.send(null);
}
function IncludeJS(sId, fileUrl, source)
{
if ( ( source != null ) && ( !document.getElementById( sId ) ) ){
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript = document.createElement( "script" );
oScript.language = "javascript";
oScript.type = "text/javascript";
oScript.id = sId;
oScript.defer = true;
oScript.text = source;
oHead.appendChild( oScript );
}
}
AjaxPage( "scrA", "b.js" );
alert( "dynamically load javascript");
alert( "dynamically load a.js and get the variable:" + str );
</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.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • StumbleUpon
  • Twitter
RSS Enjoy this Post? Subscribe to Ntt.cc

RSS Feed   RSS Feed     Email Feed  Email Feed Follow us Follow us
You can leave a response, or trackback from your own site.

25 Responses to “4 ways to dynamically load external JavaScript(with source)”

  1. [...] 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 [...]

  2. Sal Saldana says:

    Thank you, thank you, thank you!

    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 were Heaven sent.

  3. You might want to check out Include – http://javascriptmvc.com/learningcenter/include/index.html. We built it to dynamically include JavaScripts from any file, even using relative paths.

  4. Michael Lee says:

    Nice write-up Ding.

    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.

  5. Johnny says:

    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?

  6. Joe says:

    You could always use the jQuery utility function $.getScript as well. Much easier, IMO.

    http://docs.jquery.com/Ajax/jQuery.getScript

  7. mick says:

    Help please!! This works perfectly in IE 7 but not at all in Firefox…

    try
    {

    document.getElementById(“test”).src=”http://www.script.com/somescript.js”;

    }
    catch(e)
    {
    test.src=”http://www.script.com/somescript.js”;
    }

  8. The second example is incorrect. It needs to get s1 first:

    s1=document.getElementById(‘s1′); s1.src=”http://cross.domain.com/other.js”

  9. Zayar says:

    choice 2. need to remove the src=” for the strict.dtd. Otherwise it will not work in Firefox.

  10. [...] FF). The strange situation because many websites say that download with be asynchronously (e.g. http://ntt.cc/2008/02/10/4-ways-to-d…th-source.html). My Default.aspx is: protected void Page_Load(object sender, EventArgs e) { Thread.Sleep(200000); [...]

  11. [...] で、先人たちがなにをやっているのか調べてみたたところ、昨日 Delicious に登録したようにJavaScript を動的に読み込むための4つの方法が見つかりました。4つあるとは言っても、基本的には2つです。 [...]

  12. [...] 4 ways to dynamically load external JavaScript(with source) – Ntt.cc – JavaScriptを動的に読み込むための4つの方法 [...]

  13. naveen says:

    Hai
    I want to display the Image when I click on my upload button, depending upon the url specified in the field. If any one know please send the code immediately
    Thaning you

  14. Andrew says:

    THANK YOU!

    Concise, to the point and most importantly it works.

  15. student says:

    All 4 won’t work for google adsense.

  16. Thanks, your information helped me complete cross subdomain scripting project I had been getting beaten up on with IE.

  17. rFormiggs says:

    Thank you so much, this helps me so much. Some one out there will be very happy with their expensive website =)

  18. [...] 4 ways to dynamically load external JavaScript(with source) [...]

  19. SMiGL says:

    Good collection!

  20. Alexei says:

    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)

  21. dan says:

    Thanks, very useful.

  22. 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

  23. Great ways to load JavaScript. I specially liked the header manipulation. I have an example on Cross Browser Date Picker, which uses the same technique to load jQuery UI.
    Thanks

  24. Rajesh Kannan.S says:

    Hi friends,
    This post is really useful.. Thank you all the people who wrote this and posted comments.

  25. Akh Say says:

    Great Code..

Leave a Reply