jQuery API

jQuery.getScript()

jQuery.getScript( url [, success(script, textStatus, jqXHR)] ) Returns: jqXHR

Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.

  • version added: 1.0jQuery.getScript( url [, success(script, textStatus, jqXHR)] )

    urlA string containing the URL to which the request is sent.

    success(script, textStatus, jqXHR)A callback function that is executed if the request succeeds.

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts can have some impact on the current page.

Success Callback

The callback is passed the returned JavaScript file. This is generally not useful as the script will already have run at this point.

$(".result").html("<p>Lorem ipsum dolor sit amet.</p>");

Scripts are included and run by referencing the file name:

$.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
   console.log(data); //data returned
   console.log(textStatus); //success
   console.log(jqxhr.status); //200
   console.log('Load was performed.');
});

Handling Errors

As of jQuery 1.5, you may use .fail() to account for errors:

$.getScript("ajax/test.js")
.done(function(script, textStatus) {
  console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
  $( "div.log" ).text( "Triggered ajaxError handler." );
});  

Prior to jQuery 1.5, the global .ajaxError() callback event had to be used in order to handle $.getScript() errors:

$( "div.log" ).ajaxError(function(e, jqxhr, settings, exception) {
  if (settings.dataType=='script') {
    $(this).text( "Triggered ajaxError handler." );
  }
});

Caching Responses

Be default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. You can override this feature by setting the cache property globally using $.ajaxSetup():

$.ajaxSetup({
  cache: true
});

Alternatively, you could define a new method that uses the more flexible $.ajax() method.

Examples:

Example: Define a $.cachedScript() method that allows fetching a cached script:

jQuery.cachedScript = function(url, options) {

  // allow user to set any option except for dataType, cache, and url
  options = $.extend(options || {}, {
    dataType: "script",
    cache: true,
    url: url
  });

  // Use $.ajax() since it is more flexible than $.getScript
  // Return the jqXHR object so we can chain callbacks
  return jQuery.ajax(options);
};

// Usage
$.cachedScript("ajax/test.js").done(function(script, textStatus) {
  console.log( textStatus );
});

Example: Load the official jQuery Color Animation plugin dynamically and bind some color animations to occur once the new functionality is loaded.

<!DOCTYPE html>
<html>
<head>
  <style>
.block {
   background-color: blue;
   width: 150px;
   height: 70px;
   margin: 10px;
}</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<button id="go">&raquo; Run</button>

<div class="block"></div>

<script>
$.getScript("/scripts/jquery.color.js", function() {
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: "pink" }, 1000)
      .delay(500)
      .animate( { backgroundColor: "blue" }, 1000);
  });
});
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with jQuery.getScript() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to jQuery.getScript()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://netzwerkstatt.de/jqui_zweiDialoge Detlef Lindenthal

    I f you are looking for something like
    $.postScript(“myUrl”)
    analog to
        $.getScript(“myUrl”),
    but you wish method=POST, because this does not have GET's upload limitation of about 7kB:
    . . .  well, postScript() does not exist  . . . ,
    t h e n
    $.ajax({ url:”myPath/myScript.js”, dataType:”script”, type:”POST”});
    is your friend:
    myScript.js will be invoked by method=POST,
    myScript.js will be loaded and executed.

  • TM

    Using this getScript call to load a js file doesn't seem to affect $(document).ready().

    Example: something.js contains a method 'getSomething()'
    $.getScript(“something.js”)

    $(document).ready(function(){
    getSomething();
    });

    The call inside the .ready function will sometimes throw a JS error because 'getSomething()' does not exist. I know you could hook up to the call back of the script method. But in my case I can't easily do that and was surprised that the $(document).ready function fired before the script was loaded.

    • Collin

      $(document).ready(function() {
      $.getScript('something.js', function() {
      // normal document.ready stuff here (or just the stuff needing something.js)
      // and voila, your JS is sure to be loaded :)
      });
      });

    • TeMc

      Well, you maybe suprised, but it makes perfect sense.

      the $.getScript() is a function of jQuery. jQuery itself cannot do anything untill it is a loaded.
      Asuming jQuery is hardcoded in your [head] then when that file is downloaded, the DOM Is ready. Whatever you load on top of that using jQuery happends after the DOM is ready.

      There is no other way, since it can’t do getScript before the DOM is ready, since jQuery is part of that very dom.

      So, but getSomething()-call as callback in getScript(“something.js”, getSomething”)

  • http://twitter.com/agibralter Aaron Gibralter

    The arguments (data, textStatus) are not passed to the callback…

    • http://www.learningjquery.com/ Karl Swedberg

      Are you sure? I just tried it, and they seemed to be passed to the callback for me.

    • http://mike.com/ Mike

      For me neither, both are undefined when loading a script from a different domain (1.4.2).

      • http://urtak.com/ Aaron Gibralter

        Yeah, perhaps it’s the different domain. That’s the way I’m using $.getScript().

  • http://www.falise.com/ Sander Falise

    Try this if you need to load more than one script, handy in combination with loading jQuery from the Google CDN. First argument is an array of urls, second argument is a function reference to be run on complete. One load error is enough to prevent the onComplete function from being called so double check your urls!

    jQuery.getScripts = function(scripts, onComplete)
    {
    var i = 1;
    var ii = scripts.length;
    var onScriptLoaded = function(data, response) { if (i++ == ii) onComplete(); } ;
    for(var s in scripts) { $.getScript(scripts[s], onScriptLoaded); } ;
    };

    Example:

    function init()
    {
    $.getScripts(
    [
    'js/jquery.cookie.js',
    'js/jquery.easing.1.3.js',
    'js/jquery.coda-slider-2.0.js',
    'js/jquery.columnize.min.js'
    ],
    function()
    {
    // do something smart here …
    }
    );
    }

  • Gordon Johnson

    Because the data string is being passed in the url, if the data string is long (e.g. > 2080 characters from an IE6 [ICK!!] browser), the browser balks, and you will need to use the long-cut, including *

    method: “post”,

    * in the ajax call attribute pairs.

  • Surya Pentapati

    Hi,

    what will happen if .getScript fails to load the JS file. Is there any way that we can have Failure Function in .getScript along with Success?

    Thanks

  • Anonymous

    From the docs it sounds like that the call to getScript is _synchronous_, i.e. it won’t return until the script is loaded and executed. Does this mirror people’s experience?

    • http://openid-provider.appspot.com/ddellacosta Dave Della Costa

      This is definitely asychronous. It's not a great function to use if you are trying to emulate the behavior of something like a set of header include() calls.

      If you look at the jQuery source code, you can see that this is just a wrapper for the AJAX .get() function, which itself is just a wrapper for .ajax() with a certain set of parameters. In order to do what you (I think) want to do, try using the ajax() function directly with the async parameter set to “false:”

      jQuery.ajax({
      async: false,
      type: “GET”,
      url: full_path,
      data: null,
      success: success_callback,
      dataType: 'script'
      });

      http://api.jquery.com/jQuery.ajax/

      • Anonymous

        Thanks for your reply!

        What about the call-back? Can that be relied upon for knowing when the loaded script is finished executing?

        What throws me off is this sentence in the description above:

        “The callback is passed the returned JavaScript file. This is generally not useful *****as the script will already have run at this point.*****”

        This sounds like somehow the callback waits until the script has finished executing. Is that reliable? That would work for me, because then I can just have this callback increment a counter, and only when all scripts have loaded and the counter reaches a certain level, I run the JS code that depends on the scripts being loaded. Does this work?

        • http://openid-provider.appspot.com/ddellacosta Dave Della Costa

          Well, I think that is just bad wording and assumes you may want to do something with the function that maybe you don’t (frankly, I find it a bit bizarre…).

          It’s my experience that the callback executes reliably after the script is loaded/executed. But…I’ve had some strange experiences with callbacks in the past, in terms of determining exactly when they are going to execute (not with this but with other functions that pass execution off to callbacks at the end). However, I think you should be able to assume that, if you have the async flag set to false, the callback will always execute after the script is loaded. Give it a shot to make sure it’s doing what you want consistently.

          Sorry I can’t be more definite…I hope this helps!

  • George

    jQuery.getScript adds the current timestamp to the URL. Is it designed so that no cached copy is ever used?

    • Jimlay

      I’m using 1.4.2 and I’m not seeing jQuery.getScript adding any timestamp to the URL. This combined with something silly in apache sending 304 (not modified) even though the script was modified resulted in the results of getScript being cached – not entirely jQuery’s fault but your comment of it adding a timestamp led me astray.

      • Ambrauer

        Looks like this changed with v1.4+. In previous versions, the current timestamp would get appended (going to look for a bug ticket, because this seems like a regression), but in the latest, it does not. The culprit seems to be this line:
        if ( s.dataType == “script” && s.cache == null )
        which was updated to:
        if ( s.dataType === “script” && s.cache === null )
        and no longer evaluates to true (s.cache is undefined, so == will evaluate to true, wheras === to false).

  • Rick

    You can also POST via:

    jQuery.ajax({async: false,type: “POST”, url: full_path, data: null, success: success_callback, dataType: ‘script’ });

    In testing to know the script has succeeded in loading simply use a flag.

    aka:

    var successFlag; // Its a Global Flag (all one world! politics eeeysh)

    function someFunction(scriptFile)
    {
    successFlag=false; // Assume Failure

    jQuery.ajax({
    async: false,
    type: “POST”,
    url: scriptFile,
    data: null,
    success: function() {initializeScript.apply(); successFlag=true;},
    dataType: ‘script’
    });
    if(successFlag == false) { alert(‘fail’);}

  • Rick

    Or…

    function loadScript(_dnpScript)
    {
    var successflag=false;

    jQuery.ajax({
    async: false,
    type: “POST”,
    url: _dnpScript,
    data: null,
    success: function() {successflag=true;},
    dataType: ‘script’
    });
    return(successflag);
    }

  • rynoinstereo

    I just tried implementing this on a page that uses the asynchronous version of Google Analytics tracking code and this seemed to break $.getScript() from working in the sense that the callback would execute but the loaded code had not yet been executed.

  • xxchan

    What happened if you've already loaded the script and trying to load it again?

    • Paul

      It’ll reload the script file, because cache is disabled for script loads (by default), but this can be overridden.

      if ( s.dataType === “script” && s.cache === null ) {
      s.cache = false;
      }

      • dsgdsfgs

        hghgfh

      • Steve Tran

        where do you place this bit of js to avoid re-loading the script Paul?

        • http://twitter.com/rolfvandekrol Rolf van de Krol

          You can just add

          cache: true

          to the options object.

          • Ux_web

            You mean, in the loadScript options?
            I think that the loadScript func does not have that option so, where do you put the code to override the “cache: true” ?

            Thanks

  • http://julien.cayzac.name/ Julien Cayzac

    In Firefox 4.0b4pre (Minefield), calling $.getScript() or the long $.ajax() version inside another asynchronous $.ajax callback fails. It works in webkit browsers, IE and opera, tho…

  • Majid

    Wonder why no example is given of the 'data' being actually used.

  • http://twitter.com/_harddisk_ Marco Schuster

    If you develop with IE in mind, and your script is PHP generated, take care of the header() you use… it MUST be header('Content-Type: text/javascript; charset=UTF-8');, NOT utf8. Or you'll get the parser error c00ce56e, but this will not show up in any logs. You need to use the error: jQuery handler to catch this one.

    Yes, IE is crazy.

    Thanks to http://anders.tyckr.com/2008/03/04/error-c00ce56e-in-ie/ for the hint.

    • indieinvader

      Well, in this case IE is right. `utf8` is wrong, utf-8 and UTF-8, on the other hand, are correct.

  • Craig

    When loading scripts with getScript, I find it difficult to find syntax errors that cause the load to fail. Is there a way to get the usual syntax error messages in this case?

  • CharismaSilverlight

    thanks..now i remember ,sander falise comment about multiple js file was a good solution ^,^;
    thankyou..i am almost feeling like on dejavu becouse i see their comment like had me seem before..oO(from this site too ^,^..already fix..don't worry..);

  • Ken

    Let's say I want to load a script, run it once, and then attach it to the window resize event. How would I use the script that is passed to the callback function?

    $.getScript('path/to/script.js', function(s){
    $(window).resize(function() {
    // run the script again
    });
    });

  • eager_learner

    Hi everyone…
    The script works fine if the request is successfull…
    $.getScript(“test.js”, function(){
    alert(“Script loaded and executed.”);
    });

    But how can we check whether the script is successfully loaded or not… If not, i just want to halt the execution…

  • Gary NH

    I have a page that loads a script file every 30 secs (The script file is basically :
    var numbers=[12,34,56,78] ) and is written by the server.
    The file is caching so the data never changes. Any ideas?

    Gary H

    • Jimlay

      Gary,

      The simplest solution is probably to append a random string or timestamp to your request url. I had this problem and there was some discussion below about different behavior in different versions of jQuery.

      Just add ?time=TimestampToNearest30s

      Then it will cache and work to your benefit and every 30s the request will get the new value.

      • Gazzah

        Excellent – I should have remembered this from long time ago…
        added the following:
        var currentTime = new Date()
        var URL = 'dataFiles/landSideDepartures.js?time=' + currentTime.getSeconds()
        $.getScript(URL , function () {
        ….
        and it works a treat.
        Thanks Jimlay

        Gary H