jQuery / Method / .load() - Load HTML into an Element
jQuery’s .load(url, complete) fetches HTML asynchronously and replaces the selected elements’ inner contents. Add a space and selector, as in .load("fragment.html #card", complete), to insert only part of the response. Process results in the callback rather than assuming they have arrived on the next line.
Targets, return value and prerequisites
The target in the .load() API is an existing container. Its outer element remains and its contents change. An empty target selection sends no request. The return value is the original jQuery object, not a jqXHR request object or the completed HTML string.
Use the full file from the official download because the slim build excludes Ajax. Ajax exchanges data without reopening the whole page. The HTML method .load(url) differs from the old image-load event shorthand.
Create the following two files in a new practice folder. Open them through HTTP rather than double-clicking into file://. The same-origin policy compares scheme, host and port, so both files use one server here. Do not interchange localhost with 127.0.0.1 or use mismatched ports.
Complete two-file example
First save fragment.html as UTF-8. The card and an outside paragraph differ deliberately. Its harmless script only counts executions; do not substitute arbitrary external code.
<section id="card">
<h2>Local fragment</h2>
<p>This card came from fragment.html.</p>
<button type="button" class="fragment-action">Count a delegated click</button>
</section>
<p id="outside">Outside the selected card</p>
<script>window.fragmentRuns = (window.fragmentRuns || 0) + 1;</script>
Save load-demo.html in the same folder. The target #panel exists before requesting. Controls are disabled until completion to prevent duplicate actions and resetting during a request. Inside complete, this refers to each receiving target.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Load local HTML into a target</title>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<style>
body { font: 16px/1.6 sans-serif; max-width: 760px; margin: 24px auto; padding: 16px; }
button { font: inherit; margin: 4px; max-width: 100%; }
#panel { padding: 12px; border: 1px solid teal; min-height: 60px; }
pre { white-space: pre-wrap; overflow-wrap: anywhere; }
</style>
</head>
<body>
<h1>Load a complete response or selected fragment</h1>
<button type="button" id="selected">Load #card only</button>
<button type="button" id="whole">Load whole fragment</button>
<button type="button" id="error">Request missing file</button>
<button type="button" id="reset">Reset</button>
<div id="panel">Initial content</div>
<p id="clicks">delegated clicks=0</p>
<pre id="status" aria-live="polite">Ready</pre>
<script>
$(function () {
let busy = false, clicks = 0;
window.fragmentRuns = 0;
function load(url) {
if (busy) return;
busy = true;
$("#selected, #whole, #error, #reset").prop("disabled", true);
$("#status").text("Loading...");
$("#panel").load(url, function (response, textStatus, xhr) {
if (textStatus === "error") $(this).text("Load failed; try again.");
$("#status").text(`status=${textStatus}; HTTP=${xhr.status}\nscript runs=${window.fragmentRuns}`);
busy = false;
$("#selected, #whole, #error, #reset").prop("disabled", false);
});
}
$("#selected").on("click", function () { load("fragment.html #card"); });
$("#whole").on("click", function () { load("fragment.html"); });
$("#error").on("click", function () { load("missing-fragment.html"); });
$("#panel").on("click.loadLesson", ".fragment-action", function () { clicks++; $("#clicks").text(`delegated clicks=${clicks}`); });
$("#reset").on("click", function () {
$("#panel").text("Initial content"); window.fragmentRuns = 0; clicks = 0;
$("#clicks").text("delegated clicks=0"); $("#status").text("Ready");
});
});
</script>
</body>
</html>
Initial output before a request:
Ready
With Python 3 installed, open a terminal in that practice folder and run this command. If python is unavailable, check installation and command paths first. If port 8000 is occupied, choose 8001 and change the browser address too.
python -m http.server 8000 --bind 127.0.0.1
Keep the server running and open http://127.0.0.1:8000/load-demo.html. Internet is also required for the jQuery content delivery network (CDN). Stop the server with Ctrl+C in its terminal afterward. The example ran with 3.7.1 and 4.0.0, Windows Edge and Python http.server; verification used an available test port.
Compare fragments, full responses and failure
- Load #card only inserts Local fragment and its card. status=success; HTTP=200 and script runs=0. The outside paragraph is absent.
- Press Count a delegated click inside the card. delegated clicks increases through a handler registered once on #panel.
- Load whole fragment includes the outside paragraph and increases script runs by one, illustrating the script behavior below.
- Request missing file produces status=error; HTTP=404. The example displays fixed failure text with .text() instead of inserting the error response HTML.
- Retry Load #card only to recover. Reset restores initial contents and counters. Repeated loading does not bind another delegated handler.
The space in "fragment.html #card" introduces a client-side selector. "fragment.html#card" is a URL hash and is different. The selected #card element itself and its children enter #panel. The full HTML is still downloaded before selection, so this does not automatically reduce transfer size. No selector match can produce empty contents despite a successful HTTP response.
Scripts, events and GET versus POST
The API documents that script blocks may execute during HTML processing without a selector; a suffixed selector strips scripts before insertion. The two buttons verify this with a counter. Script removal does not sanitize all dangerous HTML. Insert trusted HTML and manage initialization through completion or an explicit function.
Handlers directly attached to old children do not automatically transfer to replacement children. The example delegates from the retained #panel. Repeating HTML IDs across several targets creates duplicate IDs, so review templates too. complete runs for each target; avoid duplicating global work with multiple targets.
Providing data as an object makes load use POST; otherwise it uses GET. This Python static server supports the HTML GET exercise, not a POST-processing backend. Check what the server accepts before adding an object argument. HTML insertion also differs from parsing JSON data.
Premature reads and requests that are not sent
Inspect the actual request, status and response in developer tools Network. Reading #panel immediately after load may still show old content; put post-insertion work in complete. Relative URLs use the current page location, so check folders and server addresses.
If no request occurs, inspect target .length, the full jQuery file and script errors. Other origins may require appropriate server cross-origin permissions; do not disable browser security. For cancellation, timeouts or finer control, use jQuery.ajax(), which returns the request object. Do not expect .abort() on load’s return value.




