How to Use the jQuery load() Method
jQuery's load()
method fetches HTML from a URL and uses the returned HTML to populate the selected element(s). The load()
method is unique among jQuery's methods in that it is called on a selection. To get started using this method, follow these six steps.
- Download the jQuery library from jquery.com or find a link to the latest version of jQuery by going to code.jquery.com.
- Create an HTML document that includes the jQuery library.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script> </head> <body> </body> </html>
- Inside a
script
element in your HTML document, write jQuery'sready()
function, which will wait until the selected object (the HTML document in this case) is ready before executing the code passed into it.<script> $(document).ready(function() { }); </script>
- Create a jQuery selection in the body of the function passed into the
ready()
method for the element where you want to load HTML. For example, in the following code, I've selected an element with theid
ofterms
.<script> $(document).ready(function() { $('#terms') }); </script>
- Chain the
load()
method to the selection using a.
. The only required argument is the first one, which is the URL of the document to load.<script> $(document).ready(function() { $('#terms').load('disclaimer.html'); }); </script>
- After the URL, optionally pass either of the following arguments to
load()
:- data - The data to be sent to the server. This can either be an object, like
{foo:'bar',baz:'bim' }
, or a query string, such asfoo=bar&baz=bim
. - complete - A callback function to run when the request completes.
- data - The data to be sent to the server. This can either be an object, like
The following example shows a load()
method that will load a file named disclaimer.html
and then display an alert asking you to read the disclaimer before putting the loaded HTML into an element with the id
equal to terms
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function() {
$('#terms').load('disclaimer.html', function(){
alert("Please read the disclaimer.");
});
});
</script>
<style>
#terms {
width: 500px;
height: 300px;
overflow: scroll;
border: 1px solid black;
margin: 40px auto 0px auto;
}
</style>
</head>
<body>
<div id="terms"></div>
</body>
</html>
The following image shows the result of running this example script after the alert message is dismissed and the HTML from disclaimer.html
appears.