HOWTO · JavaScript
How to Load an External HTML File Using JavaScript
Load an external HTML fragment with JavaScript fetch() or jQuery load(), and handle server, origin, and HTML safety considerations.
On this page
To load an external HTML file into a page, use JavaScript fetch() to request it and insert its response into a target element, or use jQuery load() to do both in one call. The Node.js example requests a fragment automatically when its local server starts; the browser examples load home.html after a button click. Serve the page and fragment from a web server; opening the page with a file: URL does not provide a web request environment.
Use JavaScript fetch() Method to Load an External HTML File
The following Node.js example starts a local HTTP server, requests an HTML fragment with fetch(), and prints the response body. It demonstrates the request and text conversion; the browser page below shows how to place that text in the DOM.
const http = require("node:http");
const server = http.createServer((request, response) => {
response.writeHead(200, { "Content-Type": "text/html" });
response.end("<p>Loaded fragment</p>");
});
server.listen(0, "127.0.0.1", async () => {
try {
const { port } = server.address();
const response = await fetch(`http://127.0.0.1:${port}/home.html`);
console.log(await response.text());
} catch {
console.log("Request failed");
} finally {
server.close();
}
});
<p>Loaded fragment</p>
The server chooses an available port and serves the fragment at /home.html on loopback. Node.js fetch() is not subject to the browser same-origin policy, so this request does not demonstrate browser same-origin behavior. In the browser example below, the relative path is resolved from the page URL, which may differ from the folder where your source file is stored; a different-origin server must allow the request through CORS.
Save this fragment as home.html beside the page that will load it:
<p>This content is loaded from the home page.</p>
In the page, add a button, a content target, and a status area. The click handler below uses the browser’s native fetch('./home.html'), reports a failed request in the page, and inserts the returned fragment after a successful response:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Load an HTML fragment</title>
</head>
<body>
<button type="button" id="loadHome">Load home content</button>
<p id="loadStatus" role="status"></p>
<div id="homePage"></div>
<script>
const button = document.querySelector('#loadHome');
const target = document.querySelector('#homePage');
const status = document.querySelector('#loadStatus');
button.addEventListener('click', async () => {
status.textContent = 'Loading…';
try {
const response = await fetch('./home.html');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
target.innerHTML = await response.text();
status.textContent = 'Content loaded.';
} catch (error) {
status.textContent = 'Could not load the content. Check the server and try again.';
console.error('HTML fragment request failed:', error);
}
});
</script>
</body>
</html>
The handler checks response.ok because a fetch() promise rejects for network failures, but not just because the server returned an HTTP error status; response.text() reads the response body as text. See the MDN documentation for fetch() and Response.ok. The relative request URL is resolved against the page URL. Browsers enforce the same-origin policy; a server on another origin must permit the request through CORS. Since innerHTML parses the returned string as markup, insert only content you trust; see MDN’s security guidance for innerHTML. The page source above is a browser example and has not been executed by the supplied runtime evidence; that evidence verified the Node.js server example instead.
Use jQuery load() Method to Load an External HTML File
Use the same home.html fragment above. Include jQuery before your own script, then give the element a click handler. This static page source shows the required setup and interaction; it is not an executed browser example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
</head>
<body>
<button type="button" id="loadHome">Load home content</button>
<div id="homePage">Click the button to load the fragment.</div>
<script>
$('#loadHome').on('click', function () {
$('#homePage').load('./home.html');
});
</script>
</body>
</html>
The load() method requests the URL and places the returned HTML in the selected element when the button handler runs. jQuery must load successfully before code that calls $. The URL still needs to be reachable from the server, and cross-origin requests remain subject to browser origin rules. Choose load() when a page already depends on jQuery; fetch() uses the browser API directly and does not require that library.