jQuery unveiled: the load() method

The jQuery's load() method is an Ajax method used to insert external content into an element. It is as follows:

load: function( url, params, callback ) {
  if ( typeof url !== "string" ) {
   return _load.call( this, url );

  // Don't do a request if no elements are being requested
  } else if ( !this.length ) {
   return this;

  var off = url.indexOf(" ");
  if ( off >= 0 ) {
   var selector = url.slice(off, url.length);
   url = url.slice(0, off);

  // Default to a GET request
  var type = "GET";

  // If the second parameter was provided
  if ( params ) {
   // If it's a function
   if ( jQuery.isFunction( params ) ) {
    // We assume that it's the callback
    callback = params;
    params = null;

   // Otherwise, build a param string
   } else if ( typeof params === "object" ) {
    params = jQuery.param( params, jQuery.ajaxSettings.traditional );
    type = "POST";

  var self = this;

  // Request the remote document
   url: url,
   type: type,
   dataType: "html",
   data: params,
   complete: function( res, status ) {
    // If successful, inject the HTML into all the matched elements
    if ( status === "success" || status === "notmodified" ) {
     // See if a selector was specified
     self.html( selector ?
      // Create a dummy div to hold the results
      jQuery("<div />")
       // inject the contents of the document in, removing the scripts
       // to avoid any 'Permission Denied' errors in IE
       .append(res.responseText.replace(rscript, ""))

       // Locate the specified elements
       .find(selector) :

      // If not, just inject the full result
      res.responseText );

    if ( callback ) {
     self.each( callback, [res.responseText, status, res] );

  return this;

This method accepts three parameters:

  1. url – the URL of the resource to fetch
  2. params – additional parameters
  3. callback – a callback function invoked when the insertion is completed

It performs the following actions:

  1. checks whether the URL passed in is a string or not
  2. if the request is empty, returns an instance of the method itself
  3. checks whether the URL is a valid URL
  4. sets the default HTTP request to GET
  5. checks whether the parameters passed in are a function or not; if not, builds an object literal with all the provided parameters
  6. stores a reference to the current scope in the variable self
  7. requests the remote document using the ajax() method; although the default content type for this request is text/html, this method also accepts text/plain as its content type; after the request is complete, the resource content is injected into the given element
  8. checks whether a callback function has been passed in; if so, passes the resource reference to that function.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.