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: We load the new 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("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.");
 });

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for jQuery.getScript() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • 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 ...
    }
    );
    }
  • agibralter
    The arguments (data, textStatus) are not passed to the callback...
  • Are you sure? I just tried it, and they seemed to be passed to the callback for me.
  • 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 :)
    });
    });
  • 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.