191

I want home.html to load in <div id="content">.

<div id="topBar"> <a href ="#" onclick="load_home()"> HOME </a> </div>
<div id ="content"> </div>
<script>
      function load_home(){
            document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
  }
</script>

This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Giliweed
  • 4,997
  • 8
  • 26
  • 35
  • 1
    And remember to return false as in `load_home(); return false` – mplungjan Jul 14 '13 at 04:37
  • 2
    Not too easy without libraries. Might be better off loading into an iFrame. Check this post out: http://stackoverflow.com/questions/14470135/loading-html-on-a-div-without-jquery – sgeddes Jul 14 '13 at 04:41
  • 1
    home.html is a simple web page, I just named it home. @jayharris – Giliweed Jul 14 '13 at 04:46
  • And you're trying to load everything on that page into the content element, or just place a link to the page in the content element ? – adeneo Jul 14 '13 at 04:47
  • 1
    I'm trying to load everything on that page into the content element. I edited the question. @adeneo – Giliweed Jul 14 '13 at 05:08

17 Answers17

236

I finally found the answer to my problem. The solution is

function load_home() {
     document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Neuron
  • 5,141
  • 5
  • 38
  • 59
Giliweed
  • 4,997
  • 8
  • 26
  • 35
  • 3
    Even though this is elegant and clean, I suppose it would be better if you actually created the object element through the DOM api. – David Jan 21 '15 at 19:13
  • 4
    This is slow and insecure to attack - see my answer below (was too long to fit in comment) – Sam Redway Sep 19 '15 at 17:38
  • 1
    @DavidMaes what do you suggest ? can you show a sample ? – Xsmael Nov 24 '16 at 13:12
  • 2
    While this may be insecure, if you're doing a simple "local within a folder on your desktop" development this is fine -- not everyone is running a bank website with clients handling bank account information and running into a XSS attack. Thanks for the solution, for my needs I ended up having to go another route and requiring a python server and using the regular Jquery load() function for external dynamically loaded html. But this was helpful for getting me along in my issue – rwarner Apr 07 '17 at 16:07
  • What is a difference between code in this answer and code in question (because it looks like it is identical) ? – Kamil Kiełczewski Mar 29 '19 at 17:44
  • 2
    @KamilKiełczewski `type="type/html"` is changed to `type="text/html"` – Shayan Apr 25 '19 at 19:01
  • This answer doesn't work for me, I get this error: Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. – Shayan Apr 25 '19 at 19:02
  • What if I want the whole HTML to be loaded from another address? Not a single element. – Royi Jul 22 '20 at 07:27
72

Fetch API

function load_home (e) {
    (e || window.event).preventDefault();

    fetch("http://www.yoursite.com/home.html" /*, options */)
    .then((response) => response.text())
    .then((html) => {
        document.getElementById("content").innerHTML = html;
    })
    .catch((error) => {
        console.warn(error);
    });
} 

XHR API

function load_home (e) {
  (e || window.event).preventDefault();
  var con = document.getElementById('content')
  ,   xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function (e) { 
    if (xhr.readyState == 4 && xhr.status == 200) {
      con.innerHTML = xhr.responseText;
    }
  }

  xhr.open("GET", "http://www.yoursite.com/home.html", true);
  xhr.setRequestHeader('Content-type', 'text/html');
  xhr.send();
}

based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function

Reference - davidwalsh

MDN - Using Fetch

JSFIDDLE demo

Jay Harris
  • 4,201
  • 17
  • 21
  • thanks. but my code relates to a part of a project. and sorry to say I'm not suppose to use iframe in the project work. I edited the question. have a look @jay harris – Giliweed Jul 14 '13 at 05:12
  • 1
    @Jay Harris : What about the same origin policy ? – ArunRaj Apr 29 '14 at 12:49
  • 1
    @ArunRaj you can't load a page that comes from another website within javascript bc it's a security concern. but you can load a script from your server, that will in turn load that other page and echo it back to javascript via ajax. – Jay Harris Apr 29 '14 at 19:56
  • 1
    Adding a `Content-Type` header to a `GET` request makes no sense - I think you meant `setRequestHeader("Accept", "text/html")` ? – mindplay.dk Jan 08 '19 at 13:27
71

You can use the jQuery load function:

<div id="topBar">
    <a href ="#" id="load_home"> HOME </a>
</div>
<div id ="content">        
</div>

<script>
$(document).ready( function() {
    $("#load_home").on("click", function() {
        $("#content").load("content.html");
    });
});
</script>

Sorry. Edited for the on click instead of on load.

Aaron Liske
  • 784
  • 5
  • 7
  • Hi, I tried to use this method but I can't get it to work. I can open a new question if you want. Thanks. My fiddle is here:https://jsfiddle.net/ekareem/aq9Laaew/288345/ – NoChance Dec 08 '18 at 13:39
40

Fetching HTML the modern Javascript way

This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.

/**
  * @param {String} url - address for the HTML to fetch
  * @return {String} the resulting HTML string fragment
  */
async function fetchHtmlAsText(url) {
    return await (await fetch(url)).text();
}

// this is your `load_home() function`
async function loadHome() {
    const contentDiv = document.getElementById("content");
    contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}

The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:

async function fetchHtmlAsText(url) {
    const response = await fetch(url);
    return await response.text();
}

See the fetch API documentation for more details.

droduit
  • 55
  • 1
  • 7
Lucio Paiva
  • 19,015
  • 11
  • 82
  • 104
  • 1
    For those that are having problems using this, make sure that the functions are written outside of the "window.onload" function. – Mae Cana Jun 03 '20 at 12:13
  • Show de bola é o que eu queria. – Stênio Barroso de Moraes Jun 16 '21 at 02:49
  • I've put the fetchHtmlAsText() and loadHome() functions in /reusable/js/test.js file. How do I call this function from /index.html and /article/sample.html to be able to load a common header located in /reusable/header.html? – NoMoreErrors Jul 18 '22 at 14:07
  • Tried to do this.. failed :( – NoMoreErrors Jul 18 '22 at 14:12
  • async function fetchHtmlAsText(url) { return await (await fetch(url)).text(); } // this is your `load_home() function` async function loadHeader() { const contentDiv = document.getElementById("headercontent"); contentDiv.innerHTML = await fetchHtmlAsText("/reusable/header.html"); } async function loadFooter() { const contentDiv = document.getElementById("footercontent"); contentDiv.innerHTML = await fetchHtmlAsText("/reusable/footer.html"); } async function loadHeaderfooter() { loadHeader(); loadFooter(); } window.onload = loadHeaderfooter(); – NoMoreErrors Jul 18 '22 at 14:50
  • this is my code, but only header loads but footer doesn't load. – NoMoreErrors Jul 18 '22 at 14:51
  • @NoMoreErrors please open a new question for your specific problem and avoid pasting code in the comments section next time, it's very hard for people to read and provide help. – Lucio Paiva Jul 20 '22 at 18:29
21

I saw this and thought it looked quite nice so I ran some tests on it.

It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.

I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.

In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.

Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
    <div id="content"></div>
    <script>
        /**
        * Test harness to find out the best method for dynamically loading a
        * html page into your app.
        */
        var test_times  = {};
        var test_page   = 'testpage.htm';
        var content_div = document.getElementById('content');

        // TEST 1 = use jQuery to load in testpage.htm and time it.
        /*
        function test_()
        {
            var start = new Date().getTime();
            $(content_div).load(test_page, function() {
                alert(new Date().getTime() - start);
            });
        }

        // 1044
        */

        // TEST 2 = use <object> to load in testpage.htm and time it.
        /*
        function test_()
        {
            start = new Date().getTime();
            content_div.innerHTML = '<object type="text/html" data="' + test_page +
            '" onload="alert(new Date().getTime() - start)"></object>'
        }

        //1579
        */

        // TEST 3 = use httpObject to load in testpage.htm and time it.
       function test_()
       {
           var xmlHttp = new XMLHttpRequest();

           xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                {
                   content_div.innerHTML = xmlHttp.responseText;
                   alert(new Date().getTime() - start);
                }
            };

            start = new Date().getTime();

            xmlHttp.open("GET", test_page, true); // true for asynchronous
            xmlHttp.send(null);

            // 1039
        }

        // Main - run tests
        test_();
    </script>
</body>
</html>
Sam Redway
  • 7,605
  • 2
  • 27
  • 41
  • 1
    I think instead of "accurate" you mean "precise." – pulse0ne Sep 19 '15 at 18:26
  • I mean I ran it many times and there was only a swing of a few milliseconds each time. So the times given are accurate to +- 5ms or something close to that. Sorry I may not have been entirely clear there. – Sam Redway Sep 19 '15 at 18:50
8

try

async function load_home(){
  content.innerHTML = await (await fetch('home.html')).text();
}

async function load_home() {
  let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'

  content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> <a href="#" onclick="load_home()"> HOME </a> </div>
<div id="content"> </div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
5

When using

$("#content").load("content.html");

Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server

serup
  • 527
  • 5
  • 11
5

You can use the jQuery :

$("#topBar").on("click",function(){
        $("#content").load("content.html");
});
Anup
  • 3,283
  • 1
  • 28
  • 37
4
$("button").click(function() {
    $("#target_div").load("requesting_page_url.html");
});

or

document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
Neuron
  • 5,141
  • 5
  • 38
  • 59
1
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){

    $(selector).load(argHtml);
 
});
var targetElem = document.querySelector(selector);
    targetElem.innerHTML = html;
};

var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>

this one worked for me when I tried to add a snippet of HTML to my main.html. Please don't forget to add ajax in your code pass class or id as a selector and the link to the HTML snippet as argHtml

Andrzej Sydor
  • 1,373
  • 4
  • 13
  • 28
Arshal_d
  • 116
  • 1
  • 6
0

There is this plugin on github that load content into an element. Here is the repo

https://github.com/abdi0987/ViaJS

Abdullahi
  • 134
  • 8
0
  • load html form a remote page ( where we have CORS access )
  • parse the result-html for a specific portion of the page
  • insert that part of the page in a div on current-page

//load page via jquery-ajax
$.ajax({
   url: "https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript",
   context: document.body
}).done(function(data) {

//the previous request fails beceaus we dont have CORS on this url.... just for illlustration...

   //get a list of DOM-Nodes 
   var dom_nodes = $($.parseHTML(data));

  //find the question-header
   var content = dom_nodes.find('#question-header');

  //create a new div and set the question-header as it's content 
   var newEl = document.createElement("div");
  $(newEl).html(content.html());
   
  //on our page, insert it in div with id 'inserthere'
  $("[id$='inserthere']").append(newEl);
});
                               
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>part-result from other page:</p>
<div id="inserthere"></div>
womd
  • 3,077
  • 26
  • 20
-1

This is usually needed when you want to include header.php or whatever page.

In Javascript it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Javascript function in script tag.

In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php i.e convert the php include function to Javascript function in script tag and place all your content in that included file.

Creative87
  • 125
  • 9
-1

Use this simple code

<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```
Cak Sup
  • 17
  • 9
  • w3.includeHTML() is not defined – toing_toing Feb 24 '20 at 15:28
  • 2
    For those wondering, `w3-include-HTML` is part of W3Schools.com's `W3.JS` script library (available here: https://www.w3schools.com/w3js/default.asp ). I want to point out that W3Schools (and w3.js, and `w3.includeHTML()`) are not in any way affiliated with the W3 Consortium (one of the two main groups that define the HTML+CSS+DOM standards (the other group being WHATWG). – Dai Apr 04 '20 at 12:28
-1

I use jquery, I found it easier

$(function() {
    $("#navigation").load("navbar.html");
});

in a separate file and then load javascript file on html page

NMV
  • 3
  • 2
-4

showhide.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript">
        function showHide(switchTextDiv, showHideDiv)
        {
          var std = document.getElementById(switchTextDiv);
          var shd = document.getElementById(showHideDiv);
          if (shd.style.display == "block")
          {
            shd.style.display = "none";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>"; 
          }
          else
          {
            if (shd.innerHTML.length <= 0)
            {
              shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
            }
            shd.style.display = "block";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
          }
        }
      </script>
    </head>
    <body>
      <a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
        <span style="display: block; background-color: yellow">Show</span>
      </a>
      <div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
    </body>
</html>

showhide_embedded.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript"> 
        function load()
        {
          var ts = document.getElementById("theString");
          ts.scrollIntoView(true);
        }
      </script>
    </head>
    <body onload="load()">
      <pre>
        some text 1
        some text 2
        some text 3
        some text 4
        some text 5
        <span id="theString" style="background-color: yellow">some text 6 highlight</span>
        some text 7
        some text 8
        some text 9
      </pre>
    </body>
</html>
  • 2
    Answering with an answer that doesn't correspond to the question, also its already been answered by the same person who asked it – Katler Dec 03 '14 at 14:45
-4

If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash

For ex : <iframe src="home.html" width="100" height="100"/>