Created: March-09, 2022 Sometimes, we must load
an external HTML file into another HTML file using JavaScript or jQuery, depending on project requirements. This tutorial exemplifies how to load an external HTML file using JavaScript and jQuery. HTML Code [ This content is loaded from the home page HTML Code [ The content from Home Page will be displayed here CSS Code [fetch[]
Method to Load an External HTML Fileload[]
Method to Load an External HTML FileUse JavaScript
fetch[]
Method to Load an External HTML Filehome.html
]:
Home Page
index.html
]:
Click to load content from home.html file
styles.css
]:
div{
border: 2px solid rgb[255, 0, 0];
width: fit-content;
margin: 5px;
padding: 2px 20px;
cursor: pointer;
}
button{
margin: 5px;
padding: 2px 20px;
}
p{
font-size: 14px;
}
JavaScript Code [script.js
]:
function loadHTML[]{
fetch['home.html']
.then[response=> response.text[]]
.then[text=> document.getElementById['homePage'].innerHTML = text];
}
Output:
The fetch[]
function requests the server to load data on various web pages.
We use the fetch[]
function to fetch the home.html
file from localhost. The fetch[]
method returns a Promise
.
Further, the Response
interface’s text[]
method is used, which accepts
the Response
stream, reads it and returns a Promise
which solves with the String
. Remember, the Response
is decoded by using UTF-8.
After that, we get the element whose id is homePage
by using getElementById[]
method and replace its inner HTML via .innerHTML
property with the text
.
Use jQuery load[]
Method to Load an External HTML File
HTML Code [home.html
]:
Home Page
This content is loaded from the home page
HTML Code [index.html
]:
Home Page
Click to load content from home.html file
CSS Code
[styles.css
]:
div{
border: 2px solid rgb[255, 0, 0];
width: fit-content;
margin: 20px auto;
padding: 2px 20px;
cursor: pointer;
}
p{
font-size: 14px;
}
JavaScript Code [script.js
]:
$[document].ready[function [] {
$['#homePage'].click[function [] {
$[this].load['home.html'];
}];
}];
Output:
The ready[]
method examines whether the file is completely ready or not. This event only occurs when Document Object Model has been fully loaded.
The load[]
method loads the information [data] from the server and gets the data returned by the server into the specified element.
We use the ready[]
method to
ensure that the DOM is fully ready before further operations. The home.html
file will be loaded using the load[]
method.
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.