Search code examples
jqueryconventions

jquery.load() is a shorthand for what?


I've been looking over the jQuery docs and it indicates that .load is a shorthand method, but doesn't explain what that function is.

For example, .get(url, [data], [callback(data, textStatus, XMLHttpRequest)], [dataType]) is shorthand for:

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

And this is fully explained in the documentation, but .load() does something somewhat different and it simply seems to be an outlier of the convention of the .get, .getJSON, .getScript, and .post which are similar to the above example.

What exactly is .load shorthand for?


Solution

  • $('#result').load('ajax/test.html', function(data, textStatus, xhr) {
      alert('Load was performed.');
    });
    

    is shorthand for

    if($('#result').length) {
      $.get('ajax/test.html', {}, function(data, textStatus, xhr) {
        if(textStatus=="success" || textStatus=="notmodified") {
          $('#result').html(data);
        }
        alert('Load was performed.');
      });
    }
    

    You can see what exactly .load() does by inspecting source code here: http://code.jquery.com/jquery-latest.js (It's around line 5585).

    Note: You can pass selector after your url (you have to separate it by space). If you do that not all of the response will be inserted in your document but rather only the part of target document selected by this selector.