The load() Method

Load HTML from a URL straight into an element.

Syntax$(selector).load(url, callback);

.load(url) makes a GET request and puts the returned HTML inside the selected element. It is the simplest AJAX method.

$("#content").load("page.html");

// load only part of the response
$("#content").load("page.html #section");

A callback runs when loading finishes.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A dashboard panel loads a partial HTML template into a div with .load('/partials/stats.html') on page open.
  • A tabbed interface fetches each tab's content on demand with .load() only when the user clicks that tab.
  • A comment section reloads its fragment from the server with .load() after the user submits a new comment.

More examples

Load a full partial into a div

.load() fetches the URL and injects the returned HTML directly into the matched element.

Example · html
<div id="panel"></div>
<button id="loadContent">Load panel</button>
<script>
$(function () {
  $("#loadContent").click(function () {
    $("#panel").load("/partials/dashboard-stats.html");
  });
});
</script>

Load a fragment with selector

Adding a space and selector after the URL tells .load() to extract only the matching fragment from the fetched page.

Example · html
<div id="intro"></div>
<button id="loadIntro">Load intro paragraph</button>
<script>
$(function () {
  $("#loadIntro").click(function () {
    $("#intro").load("/about.html #intro-text");
  });
});
</script>

Callback after content is inserted

The callback fires after the content is inserted; the status parameter distinguishes success from failure.

Example · html
<div id="comments"></div>
<button id="refresh">Refresh comments</button>
<script>
$(function () {
  $("#refresh").click(function () {
    $("#comments").load("/partials/comments.html", function (response, status) {
      if (status === "error") {
        $(this).text("Could not load comments.");
      } else {
        console.log("Comments loaded successfully.");
      }
    });
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.