jQuery API

jQuery.getScript()

jQuery.getScript( url, [ success(data, textStatus) ] ) Returns: XMLHttpRequest

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

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

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

    success(data, textStatus)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 callback is passed the returned JavaScript file. This is generally not useful as the script will already have run at this point.

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

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

The script can then be included and run by referencing the file name:

$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

Examples:

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-1.5.js"></script>
</head>
<body>
  <button id="go">&raquo; Run</button>

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

<script>$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: 'pink' }, 1000)
      .animate( { backgroundColor: 'blue' }, 1000);
  });
});</script>

</body>
</html>

Demo:

Example: Load the test.js JavaScript file and execute it.

$.getScript("test.js");

Example: Load the test.js JavaScript file and execute it, displaying an alert message when the execution is complete.

$.getScript("test.js", function(){
   alert("Script loaded and executed.");
 });

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
  • 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

  • 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?
  • 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/0... 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.
  • Majid
    Wonder why no example is given of the 'data' being actually used.
  • 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;
    }
  • Steve Tran
    where do you place this bit of js to avoid re-loading the script Paul?
  • 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
  • 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.
  • 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);
    }
  • 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');}
  • 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).
  • Ambrauer
    UPDATE - Pulled bug report here: http://bugs.jquery.com/ticket/...
  • wolframarnold
    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?