- How to load an external HTML file
- 3 Answers 3
- How to include another HTML file in an HTML file?
- Using JQuery load to include an HTML file
- Syntax
- Parameters
- Example
- Inner HTML file
- Main HTML file
- Output
- Using w3-include-html attribute to include an HTML file
- Syntax
- Example
- Inner HTML file
- Main HTML file
- Output
- Using the htmlinclude library to include an HTML file
- Syntax
- Example
- Inner HTML file
- Main HTML file
- Output
- Using an iframe to include an HTML file
- Syntax
- Example
- Inner HTML file
- Main HTML file
- Output
- Load an External HTML File Using JavaScript
- Use JavaScript fetch() Method to Load an External HTML File
- Use jQuery load() Method to Load an External HTML File
- Related Article — JavaScript HTML
How to load an external HTML file
Now how would I browse an external HTML file from a local hard drive and display the page preview in the div #displayPage and get the HTML tags of the file into the textarea #displayHtml ? I have no idea how to do this so please help. My fiddle is here: https://jsfiddle.net/zm6ga2ev/1/
Not how SO works. Please do research and show effort. Start with the link I gave if you do not want to upload. If you want to upload search for access file after upload
3 Answers 3
You can do this using the File API within HTML5.
Here’s a quick & dirty JS example:
function handleFileSelect(evt) < var file = evt.target.files[0]; // File inputs are an array - get the first element var reader = new FileReader(); reader.onload = function(e) < // Render the supplied file document.getElementById('displayHtml').value = e.target.result document.getElementById('displayPage').innerHTML = e.target.result; >; // Read in the HTML file. reader.readAsText(file); >; document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
A decent explanation and more comprehensive examples of how everything fits together can be found at: http://www.html5rocks.com/en/tutorials/file/dndfiles/
@user5384372 in my opinion, this should be the accepted answer: this answer includes examples and links to external sources. the original question did not specify any external libraries and this answer does not use any. plus, this answer comes with a complete working example in the jsfiddle link.
Let the user upload the html file into your server .
Now , you can use this code to load html file into the div tag
document.getElementById("displayPage").innerHTML='';
Or simply use jquery .load() function
You just .load other page content into your div.
//Load full document $('#displayPage').load('http://same-domain.com/next-page.html'); // You can use any CSS selector to load only part of page $('#displayPage').load('http://same-domain.com/next-page.html #some-inner-id > *');
If #displayPage element is not found in DOM, than no request will be performed! If #some-inner-id is not found in request page DOM, than you get empty content.
Loaded page must allow Cross-Origin request (usually it means same domain request). Look here for Cross-Origin requests.
How to include another HTML file in an HTML file?
In this tutorial, we shall learn to include another HTML file in an HTML file.
Various methods are available to include another HTML file in an HTML file. Let us quickly go through the techniques that have support on the web.
Using JQuery load to include an HTML file
In this section, we shall check how to use JQuery’s load method to include an HTML file.
Users can follow the syntax below to use this method.
Syntax
The wrapper appends the new HTML file that jQuery loads.
Parameters
- wrapper − ID of the DOM element that includes the new HTML content.
- htmlfile − The new HTML file name.
Example
The program requires two HTML files. One is the main HTML file to load the new HTML file. Next is the new HTML file. Place both files in the exact location.
Define a wrapper DOM element in the main HTML file to append the new HTML file. Using the jQuery load technique load the new HTML file and set it inside the wrapper DOM.
Inner HTML file
html> body> h3>This is an HTML page from same directoryh3> body> html>
Main HTML file
html> head> script src="https://code.jquery.com/jquery-1.11.3.min.js">script> script> $(function() < $("#includeHtml").load("result.html"); >); script> head> body> h2>Program to include another HTML file in this HTML using i>JQuery loadi>h2> div id="includeHtml">div> body> html>
Output
Using w3-include-html attribute to include an HTML file
In this section, let us check how to use the w3-include-html attribute to include an HTML file.
Users can follow the syntax below to use this method.
Syntax
Includes a wrapper DOM with the attribute w3-include-html having the new HTML file name as the value.
//Read the attribute fileName = domEl.getAttribute("w3-include-html"); //Make XMLHttpRequest with the attribute value xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() < //If the request is successful, load the new HTML. Else throw 404 error and try again if (this.readyState == 4) < if (this.status == 200) if (this.status == 404) /* Remove the attribute and invoke the function again*/ domEl.removeAttribute("w3-include-html"); addHTML(); > xmlHttp.open("GET", fileName, true); xmlHttp.send();
The syntax reads the w3-include-html attribute value and loads the new HTML with a XMLHttpRequest.
Example
In this example, create a new HTML and a default HTML file. The default HTML file contains a div element with attribute w3-include-html which contains the new HTML file name.
The program reads the w3-include-html attribute value, makes an XMLHttpRequest with the file name, and loads the file.
A New HTML file renders inside the w3-include-html wrapper DOM after a successful file load. Else user gets an error message, and the program loads the file again.
Inner HTML file
html> body> header>b>HTML 2 HEADERb>header> div style="height: 100px;">div> footer>b>HTML 2 FOOTERb>footer> body> html>
Main HTML file
html> body> h2>Program to include another HTML file in this HTML using i>w3-include-htmli>h2> div w3-include-html="result.html">div> script> function addHTML() < var el, i, domEl, fileName, xmlHttp; /*Iterate all DOM*/ el = document.getElementsByTagName("*"); for (i = 0; i < el.length; i++) < domEl = el[i]; /*find the element having w3-include-html attribute*/ fileName = domEl.getAttribute("w3-include-html"); if (fileName) < /*http request with attribute value as file name*/ xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() < if (this.readyState == 4) < if (this.status == 200) < domEl.innerHTML = this.responseText; >if (this.status == 404) < domEl.innerHTML = "Page not found."; >/* Remove the attribute and invoke the function again*/ domEl.removeAttribute("w3-include-html"); addHTML(); > > xmlHttp.open("GET", fileName, true); xmlHttp.send(); /*function ends*/ return; > > > addHTML(); script> body> html>
Output
Using the htmlinclude library to include an HTML file
In this section, we shall check how to use the htmlinclude library to include an HTML file.
Users can follow the syntax below to use this method.
Syntax
The syntax adds the javascript library file URL.
The include tag src contains the new HTML file name.
//Getting include attribute value let includes = document.getElementsByTagName('include'); for(var i=0; i); > function load_file(filename, callback) < fetch(filename).then(response =>response.text()).then(text => callback(text)); >
The syntax loads the source of the tag «include» using the fetch method.
Example
In this example, the htmlinclude library is available in the header. Creating an include tag with the new file name as the src attribute value.
Coming to the script, loading the include tag src value with the fetch method. If you get any error using fetch, try to get help from nodejs or any other program IDE.
Inner HTML file
html> body> b>htmlinclude library included this HTML fileb> body> html>
Main HTML file
html> head> script src="https://unpkg.com/htmlincludejs">script> head> body> h2>Program to include another HTML file in this HTML using i>htmlinclude libraryi>h2> include src="./result.html">include> script> let includes = document.getElementsByTagName('include'); for (var i = 0; i < includes.length; i++) < let include = includes[i]; load_file(includes[i].attributes.src.value, function(text) < include.insertAdjacentHTML('afterend', text); include.remove(); >); > function load_file(filename, callback) < fetch(filename).then(response =>response.text()).then(text => callback(text)); > script> body> html>
Output
Using an iframe to include an HTML file
In this section, let us check how to use an iframe to include an HTML file.
Users can follow the syntax below to use this method.
Syntax
The iframe tag includes the new HTML file name in the src.
Example
In this example, create a sample HTML file to include and main HTML file. The approach adds an iframe with the new HTML file name as the source value in the new HTML body.
The iframe loads the new HTML content inside the main HTML file.
Inner HTML file
html> body> div style="background-color: skyblue;">iframe included this HTML filediv> body> html>
Main HTML file
html> head> h2>Program to include another HTML file in this HTML using i>iframei>h2> style> iframe[iframetag] < border: none; >style> head> body> div id="iframeDiv"> iframe src="result.html" iframetag>iframe> div> body> html>
Output
This tutorial introduced four methods to include a new HTML file in an HTML file. The iframe method is simple to implement. Users can choose the jQuery load method if they need a jQuery method.
Load an External HTML File Using JavaScript
- Use JavaScript fetch() Method to Load an External HTML File
- Use jQuery load() Method to Load an External HTML File
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.
Use JavaScript fetch() Method to Load an External HTML File
html lang="en"> head> title>Home Pagetitle> head> body> p>This content is loaded from the home pagep> body> html>
html lang="en"> head> script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> script> script src="./script.js">script> link rel="stylesheet" href="./styles.css"> head> body> button onclick="loadHTML()"> Click to load content from home.html file button> div id="homePage"> p>The content from Home Page will be displayed herep> div> body> html>
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); >
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 lang="en"> head> title>Home Pagetitle> head> body> p>This content is loaded from the home pagep> body> html>
html lang="en"> head> script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> script> script src="./script.js">script> link rel="stylesheet" href="./styles.css"> head> body> div id="homePage"> Home Page p>Click to load content from b>home.htmlb> filep> div> body> html>
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'); >); >);
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.
Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.