.load() is the simplest way to pull HTML from a server and drop it into a page region. This tutorial covers the official signature, automatic DOM insertion, GET vs POST based on the data argument, URL fragment selectors, the complete callback with responseText and jqXHR, script execution rules, empty-set behavior, and when to prefer $.get() or full $.ajax().
01
HTML Injection
.load(url)
02
Fragments
url #selector
03
GET / POST
data switches method
04
complete
After insertion
05
Scripts
Run or strip
06
Chainable
Returns jQuery
Fundamentals
Introduction
Tab panels, infinite-scroll footers, admin sidebars — many UI patterns need a chunk of HTML from the server without reloading the whole page. jQuery solves that in one line: $( "#panel" ).load( "sidebar.html" ). The method fetches the URL, and on success replaces the inner HTML of every matched element with the response.
.load() is roughly $.get() plus .html() with the wiring done for you. Unlike global Ajax shorthands, it is a collection method — you call it on a jQuery selection, not on jQuery itself. It returns the same jQuery object for chaining (add classes, bind events). When you need a fragment of a remote page — not the whole document — append a selector after a space in the URL string.
Concept
Understanding .load()
.load() sends an Ajax request and inserts the returned HTML into matched elements. The request runs only if the jQuery collection contains at least one element — an empty selection is a no-op and no network call is made.
On success (textStatus is "success" or "notmodified"), jQuery sets each element’s contents via .html(). If you provide a complete callback, it fires once per matched element after insertion, with this set to that DOM node.
💡
Beginner Tip
Check status === "error" inside the complete callback to show user-friendly messages — .load() does not remove old content on failure, so display errors in a separate element. Prior to jQuery 3.0, .load() also named the window load event handler; modern jQuery removed that conflict.
No request sent — verify selector matches DOM first
Need jqXHR / .fail()
Use $.get() or $.ajax() instead
Compare
📋 .load() vs $.get() vs .html() vs fetch()
Four ways to put HTML on the page — pick based on whether the source is a URL, a string, or needs manual handling.
.load()
url → element
$("#el").load(url) — fetch and inject in one step; supports fragment selector; returns jQuery
$.get()
url → callback
$.get(url, fn) — returns jqXHR; you update the DOM yourself; no fragment syntax
.html()
string → element
$("#el").html(htmlString) — local string only; no network request
fetch()
native API
fetch(url).then(r => r.text()) — manual insert; no jQuery global Ajax events
Use .load() when you have a target element and a URL returning HTML. Use $.get() when you need jqXHR chaining or non-HTML responses. Use .html() for strings already in memory. Use fetch() without jQuery.
Hands-On
Examples Gallery
Five progressive examples from a basic HTML load through fragment selectors, POST data, error handling in the complete callback, and a tab-style lazy panel. Each links to a Try-it lab where you can edit and run the code in the browser.
📚 Core Patterns
Fetch HTML and inject it into matched elements.
Example 1 — Basic .load(url)
Official one-liner: load a remote HTML page into a container element.
jQuery
$( "#result" ).load( "https://httpbin.org/html" );
// Equivalent intent:
// GET the URL → on success, set #result innerHTML to response
GET https://httpbin.org/html → HTML inserted into #result
#result shows the remote page body (e.g. h1 heading and paragraph)
Uses GET — no data argument provided
How It Works
If #result does not exist, nothing happens — no Ajax call. On success, jQuery replaces the element’s contents. Scripts in the full response may execute (unlike fragment loads).
Example 2 — Load a page fragment — url selector
Official fragment syntax: fetch a page but insert only the matching portion.
jQuery
// Space separates URL from selector — only h1 is inserted
$( "#snippet" ).load( "https://httpbin.org/html h1" );
// Same pattern for local partials:
$( "#new-projects" ).load( "/resources/load.html #projects li" );
Full document fetched → jQuery parses with .innerHTML rules
Only "h1" nodes extracted → inserted into #snippet
Scripts stripped — not executed with selector suffix
How It Works
jQuery downloads the full document, parses it, runs the selector against the parsed tree, and inserts the match. The rest is discarded. Browsers may filter <html>, <head>, or <body> during parsing — inserted markup may differ slightly from viewing the URL directly.
Example 3 — POST with data object
Official pattern: passing data switches the request to POST.
jQuery
$( "#feeds" ).load(
"feeds.php",
{ limit: 25 },
function( responseText, status, jqXHR ) {
alert( "The last 25 entries in the feed have been loaded" );
}
);
// Arrays in POST body:
$( "#objectID" ).load( "test.php", { "choices[]": [ "Jon", "Susan" ] } );
data object present → POST feeds.php with limit=25 in body
Server returns HTML → inserted into #feeds
complete callback runs after insertion (once per matched element)
How It Works
The second argument is serialized with $.param() and sent as the POST body. The third argument is the complete callback — not a jqXHR method. It fires after HTML insertion on success.
📈 Errors & UX Patterns
Handle failures and load content on user interaction.
Example 4 — Error handling in complete callback
Adapted from the official docs: check status === "error" and show a message elsewhere.
jQuery
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status === "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
} );
// On success, #success gets HTML; on error, #error shows status
404 or network failure → status === "error"
#error shows "Sorry but there was an error: 404 Not Found"
#success may stay empty — old content not cleared on error
How It Works
The complete callback runs for both success and failure. Unlike jqXHR .fail(), you inspect textStatus yourself. Show errors in a dedicated element so users know the load failed.
Example 5 — Lazy-load a tab panel on first click
Common UX pattern: defer network cost until the user opens a section.
jQuery
var loaded = false;
$( "#tab-details" ).on( "click", function() {
if ( loaded ) {
return;
}
$( "#details-panel" )
.html( "<p>Loading…</p>" )
.load( "https://httpbin.org/html h1", function( response, status ) {
if ( status === "success" ) {
loaded = true;
$( this ).prepend( "<small>Loaded once</small><br>" );
}
} );
} );
First click → "Loading…" then fragment h1 inserted
Second click → no-op (loaded flag)
.complete callback: this === #details-panel DOM element
How It Works
Combine placeholder HTML, fragment load, and a guard flag for one-time fetch. Inside complete, this refers to the element being updated — use it instead of closing over selectors.
Applications
🚀 Common Use Cases
Tab panels — load each tab’s HTML on first activation instead of all at once.
Modals & drawers — fetch form partials into a dialog container on open.
Pagination — replace a list region with the next page HTML from the server.
Admin widgets — pull dashboard snippets into sidebar slots.
Help tooltips — load expanded help content on hover or click.
Legacy server templates — reuse existing PHP/JSP partials that return HTML fragments.
🧠 How .load() Works Internally
1
Verify matched elements
If the jQuery collection is empty, return immediately — no Ajax request is sent.
selector
2
Parse URL & method
Split url selector on first space for fragment mode. Use POST if data provided, else GET.
GET/POST
3
Ajax fetch HTML
Delegates to $.ajax() with dataType: "html". Global ajaxStart / ajaxStop fire unless opted out.
$.ajax()
4
Extract fragment
If selector suffix present, parse response and pull matching nodes — scripts stripped. Full load may execute scripts via .html().
fragment
5
Insert & complete
On success, set each element’s HTML. Fire complete(responseText, textStatus, jqXHR) once per element; this is that node.
complete
6
👉
Return jQuery collection
Chain further jQuery methods. On error, insertion is skipped — handle via complete or global ajaxError.
Important
📝 Notes
.load() is a collection method — call it on $(selector), not on jQuery globally.
Returns the jQuery collection, not jqXHR — use the complete callback for status details.
Empty set: no matched elements means no Ajax request.
Fragment URL: space separates URL from selector — scripts in fragment loads do not execute.
Full URL load: scripts may run before discard — only load trusted HTML.
POST when data provided — plain object or string in the second argument.
Prior to jQuery 3.0, .load() conflicted with the window load event binding — removed in 3.0.
Same-origin: cross-domain loads require CORS unless using JSONP (not supported by .load()).
Compatibility
Browser Support
.load() is part of jQuery’s core Ajax module — not a native DOM API. It works wherever jQuery’s Ajax transport runs: all browsers supported by your jQuery version, including legacy IE with supported jQuery builds.
✓ jQuery 1.0+
jQuery .load() method
Supported in jQuery 1.x, 2.x, and 3.x across all modern browsers and IE with supported jQuery builds. URL fragment selector since early versions. Window load event naming conflict resolved in jQuery 3.0. Script execution rules differ for full vs fragment loads.
100%With jQuery
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
.load()Universal
Bottom line: Safe in any jQuery project for same-origin HTML partials. Use $.get() when you need jqXHR .fail(); fetch() + insertAdjacentHTML when jQuery is not loaded.
Wrap Up
Conclusion
.load() is the fastest path from URL to visible HTML in a container. Learn the signature (url, data, complete), use the space-separated fragment syntax for partials, and check status in the complete callback when errors matter.
Continue with the jQuery.param() tutorial to see how POST data is encoded, or review jQuery.get() when you need jqXHR chaining without automatic DOM insertion.
Verify the target element exists before calling .load()
Use fragment selectors to avoid inserting full page chrome
Check status === "error" in complete and show feedback
Lazy-load heavy panels on first user interaction
Load HTML only from origins you trust — scripts may execute
❌ Don’t
Load arbitrary user-supplied URLs — that is a remote HTML injection risk
Assume failed loads clear old content — handle errors explicitly
Rely on jqXHR .fail() — .load() returns jQuery, not jqXHR
Use full-page loads when a fragment selector would suffice (script safety)
Confuse with $(window).on("load", fn) — different API in jQuery 3.x
Summary
Key Takeaways
Knowledge Unlocked
Six things to remember about .load()
URL in, HTML in element.
6
Core concepts
html01
Auto Insert
HTML → element
Core
#02
Fragments
url selector
Partial
POST03
data = POST
Body payload
Method
fn04
complete
status, jqXHR
Callback
js05
Scripts
Run or strip
Security
$06
Chainable
Returns jQuery
API
❓ Frequently Asked Questions
jQuery .load() is a collection method that fetches HTML from a URL and inserts it into each matched element. Call $("#panel").load("/partial.html") — jQuery sends an Ajax request, and on success sets the element's inner HTML to the response. It is roughly equivalent to $.get() plus .html() but with an implicit success handler built in. Returns the jQuery collection for chaining.
$.get() is a global function that returns jqXHR and passes parsed data to your callback — you must manually update the DOM. .load() is a method on a jQuery selection that automatically inserts returned HTML into those elements. .load() also supports a URL fragment selector ("page.html #sidebar") that $.get() does not. Use .load() when the goal is inject HTML into a container; use $.get() when you need to process the response yourself.
If you pass a data argument (plain object or string), jQuery uses POST and sends that data in the request body. With only a URL (and optional complete callback), .load() uses GET. This mirrors $.get() vs $.post() behavior — data presence switches the method.
If the url string contains a space, the part after the first space is treated as a jQuery selector applied to the fetched document. $("#result").load("article.html #comments") fetches article.html, extracts only the #comments element, and inserts that into #result. The rest of the remote document is discarded. Scripts in fragment loads are stripped and not executed.
When loading a full page URL without a selector suffix, scripts pass through .html() and execute before being discarded. When using a selector suffix ("url #fragment"), scripts are stripped before DOM insertion and do not run. Never .load() URLs you do not trust — executed scripts have full page privileges.
If the jQuery collection is empty — for example $("#missing").load(url) when #missing does not exist — the Ajax request is not sent at all. Always verify your target element exists before calling .load().
Did you know?
.load() has existed since jQuery 1.0 as the simplest Ajax helper — before $.get() and $.post() became the preferred global shorthands for custom handling. Prior to jQuery 3.0, the same method name also bound the window load event when passed a function — jQuery disambiguated by argument type. The URL fragment trick ("page.html #section") is unique to .load() among common shorthands and is still the easiest way to pull a partial from a legacy server-rendered page.