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 jQuery.ajax({ 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:
url
– the URL of the resource to fetchparams
– additional parameterscallback
– a callback function invoked when the insertion is completed
It performs the following actions:
- checks whether the URL passed in is a string or not
- if the request is empty, returns an instance of the method itself
- checks whether the URL is a valid URL
- sets the default HTTP request to GET
- checks whether the parameters passed in are a function or not; if not, builds an object literal with all the provided parameters
- stores a reference to the current scope in the variable
self
- requests the remote document using the
ajax()
method; although the default content type for this request istext/html
, this method also acceptstext/plain
as its content type; after the request is complete, the resource content is injected into the given element - checks whether a callback function has been passed in; if so, passes the resource reference to that function.