TExcelTAD
Home › jQuery › jQuery load()

jQuery load() Method

.load() is the simplest AJAX method in jQuery. It requests a URL, takes the HTML that comes back, and puts it inside the selected element — one line, no callbacks required.

js
$(selector).load(url, data, complete);
Argument Meaning
url Address of the HTML to load. May end with a space and a selector to load only a fragment: "page.html #main"
data (optional) A string or object sent with the request. An object makes it a POST, otherwise it is a GET
complete (optional) function (responseText, textStatus, jqXHR) — runs after the content has been inserted (also on error)

Loading a snippet

In a real site you would write $("#news").load("news.html"). Here the "file" is a data: URL built from an HTML string, so the example works without a server:

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    #news { border: 1px solid #ccc; padding: 8px 12px; min-height: 40px; margin-top: 8px; border-radius: 6px; }
  </style>
</head>
<body>
  <button id="load">Load latest news</button>
  <div id="news">Click the button…</div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    // pretend this is the file "news.html" on your server
    const newsHtml = `
      <h3>Latest news</h3>
      <ul>
        <li>jQuery 3.7.1 released with bug fixes</li>
        <li>New lessons added to ExcelTAD</li>
      </ul>`;
    const newsUrl = "data:text/html;charset=utf-8," + encodeURIComponent(newsHtml);

    $("#load").on("click", function () {
      $("#news").text("Loading…").load(newsUrl, function (response, status, xhr) {
        console.log("status:", status, "| chars received:", response.length);
      });
    });
  </script>
</body>
</html>

Loading only part of a page

Add a space and a selector after the URL, and jQuery inserts only the matching part of the response. This is handy for reusing a section of an existing page — for example just the #menu from layout.html.

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 14px; }
    .slot { border: 1px dashed #0769ad; padding: 6px 10px; margin: 6px 0; min-height: 24px; }
  </style>
</head>
<body>
  <button id="a">Load #faq</button>
  <button id="b">Load .price</button>
  <button id="c">Load everything</button>
  <div class="slot" id="out">—</div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    // the whole "page.html"
    const page = `
      <header><h1>Coffee Shop</h1></header>
      <section id="faq"><b>FAQ:</b> We open at 7 am every day.</section>
      <p class="price">Espresso: $2.50</p>
      <p class="price">Latte: $3.80</p>
      <footer>© Coffee Shop</footer>`;
    const pageUrl = "data:text/html;charset=utf-8," + encodeURIComponent(page);

    function loadPart(selector) {
      const url = selector ? pageUrl + " " + selector : pageUrl;
      $("#out").load(url, function () {
        console.log("loaded", selector || "(whole page)", "→", $(this).children().length, "element(s)");
      });
    }
    $("#a").on("click", () => loadPart("#faq"));
    $("#b").on("click", () => loadPart(".price"));
    $("#c").on("click", () => loadPart(""));
  </script>
</body>
</html>

Note: When a selector is given, <script> elements in the loaded HTML are removed before insertion. Without a selector, scripts in the response are executed. Only load HTML from sources you trust.

Handling errors

.load() has no .fail(), but the complete callback receives the status. Check it to show a friendly message. The example below uses a tiny fake server (see the AJAX Intro lesson) that answers /pages/... URLs — one of them returns 404.

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 14px; }
    nav a { margin-right: 10px; }
    nav a.active { font-weight: bold; color: #c0392b; }
    #content { margin-top: 8px; padding: 10px; background: #f4f6f8; border-radius: 6px; min-height: 60px; }
  </style>
</head>
<body>
  <nav>
    <a href="/pages/home">Home</a>
    <a href="/pages/about">About</a>
    <a href="/pages/oops">Broken link</a>
  </nav>
  <div id="content">Choose a page.</div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    // ---- fake server ----
    const pages = {
      "/pages/home": "<h3>Home</h3><p>Welcome to our tiny site.</p>",
      "/pages/about": "<h3>About</h3><p>We have been loading HTML with jQuery since 2006.</p>"
    };
    $.ajaxTransport("+*", function (options) {
      if (!options.url.startsWith("/pages/")) return;
      let t;
      return {
        send(headers, complete) {
          t = setTimeout(() => {
            const html = pages[options.url];
            if (html) complete(200, "OK", { text: html });
            else complete(404, "Not Found", { text: "" });
          }, 300);
        },
        abort() { clearTimeout(t); }
      };
    });
    // ---------------------

    $("nav").on("click", "a", function (e) {
      e.preventDefault();                       // stay on this page
      const url = $(this).attr("href");
      $(this).addClass("active").siblings().removeClass("active");
      $("#content").text("Loading…").load(url, function (response, status, xhr) {
        if (status === "error") {
          $(this).html("<p style='color:#c0392b'>Sorry, that page could not be loaded (" +
                       xhr.status + " " + xhr.statusText + ").</p>");
        }
        console.log(url, "→", status, xhr.status);
      });
    });
  </script>
</body>
</html>

This is the essence of a classic "AJAX navigation": links stay real links (useful without JavaScript and for search engines), but jQuery intercepts the click and loads only the content area.

load() at a glance

Feature Behaviour
Method GET, or POST if data is an object
Response type Always treated as HTML
Where it goes Replaces the content of every selected element
Fragment "url #selector" inserts only the matches
Scripts Run without a selector; stripped with one
Errors Check status === "error" in the complete callback

Tip: .load() is great for small, server-rendered pieces of HTML. When the server returns data (JSON) rather than markup, use $.getJSON() or $.ajax() and build the HTML yourself.

Note: Do not confuse this with the old .load(handler) event shorthand (for images or window load), which was removed in jQuery 3. Use .on("load", handler) for that.

Test yourself

What does $("#side").load("layout.html #menu") do?

  1. Loads layout.html into a new window
  2. Loads layout.html and inserts only the #menu part into #side
  3. Loads #menu into layout.html
  4. Throws an error because of the space

When does .load() send a POST request?

  1. Never
  2. When the data argument is an object
  3. When the URL ends with .php
  4. When a callback is passed

How do you detect a failed .load() call?

  1. Chain .fail()
  2. Check status === "error" in the complete callback
  3. It throws an exception
  4. Use try/catch around it