jQuery Load
The load() method is the simplest AJAX tool in jQuery. It fetches HTML from a URL and inserts it directly into the element you selected, one line, no callbacks required for the basic case.
Loading content into an element
Unlike $.get() and $.post(), which are global functions, load() is called on a jQuery selection. Whatever HTML the server returns is placed inside the matched element, replacing its current content. This makes load() perfect for pulling in a chunk of a page, a sidebar, a product description, a list of comments, without rebuilding it by hand.
Basic load() syntax
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="content">Original content goes here.</div>
<script>
$("#content").load("article.html");
</script>
</body>
</html>That single line asks the server for article.html and drops the whole file into the element with the id content. If content already had text or markup inside it, that old content is thrown away and replaced.
Loading only part of a file
You often do not want an entire file, just one section of it. load() lets you add a CSS selector after the URL, separated by a space. jQuery fetches the file, finds the matching piece, and inserts only that.
Grabbing a single fragment
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="content">Original content goes here.</div>
<script>
// Load only the element with id="summary" from article.html
$("#content").load("article.html #summary");
</script>
</body>
</html>Running code after the load finishes
Because loading happens asynchronously, you sometimes need to know when it is done, maybe to show a message or hide a spinner. load() accepts an optional callback function that runs after the request completes. That callback receives three useful arguments.
Reacting to success or failure
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="content">Original content goes here.</div>
<script>
$("#content").load("article.html", function(responseTxt, statusTxt, xhr) {
if (statusTxt === "success") {
alert("Content loaded successfully!");
}
if (statusTxt === "error") {
alert("Error: " + xhr.status + " " + xhr.statusText);
}
});
</script>
</body>
</html>- Use load() when the server sends back ready made HTML you want to display.
- Add a selector after the URL to insert only one part of a page.
- Add a callback when you need to run code once the content has arrived.
- The file you load must live on the same domain unless CORS is configured.
Exercise: jQuery Load
What does the .load() method fundamentally do?