68

I'm quite sure this a common question, but I'm pretty new to JS and am having some trouble with this.

I would like to load x.html into a div with id "y" without using iframes. I've tried a few things, searched around, but I can't find a decent solution to my issue.

I would prefer something in JavaScript if possible.

starball
  • 20,030
  • 7
  • 43
  • 238
MapWeb
  • 745
  • 1
  • 6
  • 6
  • If that's the only way of doing it, I guess it would be okay. I've never used jQuery though.. – MapWeb Aug 20 '10 at 21:41
  • 1
    Its not the *only* way, but it does abstracts away most of the complexity a problem like this brings. Also, remember that because of security concerns you cannot load HTML from other sites (different domain names) with Javascript – Yi Jiang Aug 20 '10 at 21:46

8 Answers8

115

Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.

var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
    if (this.readyState!==4) return;
    if (this.status!==200) return; // or whatever error handling you want
    document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();

If you need IE<8 compatibility, do this first to bring those browsers up to speed:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
        return new ActiveXObject('MSXML2.XMLHttp');
    };
}

Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.

bobince
  • 528,062
  • 107
  • 651
  • 834
  • 21
    This is a good answer because the question wasn't about JQuery. There are some cases in which you *can't* use JQuery or some framework to do this. – Nate Reed Nov 26 '12 at 18:17
  • Strange, I get a `NS_ERROR_DOM_BAD_URI: Access to restricted URI denied` error – Costa Michailidis Jun 17 '14 at 02:33
  • 3
    @Costa: sounds like you are trying to do a cross-site XMLHttpRequest. That's disallowed for security reasons, unless the target site opts in. – bobince Jun 18 '14 at 00:26
  • 4
    Today's browsers won't let you XHR onto the filesystem. You will need to set up a test web server. – bobince Jun 18 '14 at 23:02
  • @bobince, great answer, Do you know why the scripts of the imported file do not render? Actually by using your answer I can import just html, but not generated content, which is rendred from a json file. Thanks for your help. – digitai May 19 '17 at 16:18
  • @datelligence: if writing `` to `innerHTML` executed the script, then the script would keep executing again and again every time your wrote `innerHTML` to move markup between elements, and it's unclear what context the document would be in for code executed as a consequence. (Normally code executing in a ` – bobince May 21 '17 at 21:00
  • How would you make this work with an external file, such as one loaded from a Nextcloud instance? – RolandiXor Jul 05 '18 at 05:26
79

jQuery .load() method:

$("#y").load("x.html");
brasofilo
  • 25,496
  • 15
  • 91
  • 179
Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
  • 18
    jQuery is great and does all things. –  Feb 04 '14 at 17:25
  • 2
    Why this answer is not marked as answered, for me it worked like a charm! This is amazing that only jquery is needed to make a dynamic homepage. – Mr. Blond Jan 24 '15 at 21:28
  • 9
    @EdgarsŠturms It may work, and be concise, but it isn't the correct answer because the question did not ask for a jQuery solution. – Matt Apr 05 '16 at 10:40
  • OP never said it couldn't be jquery (many people ask/search for jquery by 'javascript'), and clarified the following: "If that's the only way of doing it, I guess it would be okay. I've never used jQuery though.." So no, this is definitely the best answer. – Tyler Montney May 07 '18 at 17:41
  • I used this to load x.html which in turn loads x.js . This JS works because I set an alert() on the first line, but the functions defined in x.js do not work, any idea why? – golimar Oct 29 '20 at 16:18
27

Using fetch

<script>
fetch('page.html')
  .then(response=> response.text())
  .then(text=> document.getElementById('elementID').innerHTML = text);
</script>

<div id='elementID'> </div>

fetch needs to receive a http or https link, this means that it won't work locally.

Note: As Altimus Prime said, it is a feature for modern browsers

  • 3
    +1 for being a great answer for a modern browser, but be warned: after a couple hours of testing I could not make this work in Cordova 9.0.0 and had to resort to old fashioned `XMLHttpRequest` which worked fine. I don't think that Cordova supports `fetch` yet. – Altimus Prime Sep 22 '19 at 02:36
  • 1
    Great answer! It worked for me developing in VSCode and live-server for testing in Windows Powershell. Access to local files using Javascript required tweaking security policy settings like so: https://stackoverflow.com/questions/49772982/is-setting-executionpolicy-to-unrestricted-for-currentuser-a-security-breach. – Sun Bee Mar 26 '21 at 23:24
10

2021

Two possible changes to thiagola92's answer.

  1. async await - if preferred

  2. insertAdjacentHTML over innerText (faster)

    <script>
    async function loadHtml() {
         const response = await fetch("page.html")
         const text = await response.text()
         document.getElementById('elementID').insertAdjacentText('beforeend', text)
    }
    
    loadHtml()
    </script>
    <!-- ... -->
    <div id='elementID'> </div>
    
Martin Meeser
  • 2,784
  • 2
  • 28
  • 41
  • 1
    Good to see this use of async/await. – Tim Erickson Sep 13 '21 at 15:13
  • Isn't `fetch('page.html').then(response => response.text())` already asynchronous? I mean, the key word "async" makes your function return a `Promise` and when using `fetch()` it already returns a promise, right? – Thiago Lages de Alencar Feb 19 '22 at 04:13
  • 1
    @thiagola92 yes it is just another way of "writing" it down, "improvement" might be not a good choice of wording (edited). Thank you for pointing that out. In general async await has some advantages IMHO: - readability - debugability - try-catch-ability. – Martin Meeser Feb 19 '22 at 15:16
7

I'd suggest getting into one of the JS libraries out there. They ensure compatibility so you can get up and running really fast. jQuery and DOJO are both really great. To do what you're trying to do in jQuery, for example, it would go something like this:

<script type="text/javascript" language="JavaScript">
$.ajax({
    url: "x.html", 
    context: document.body,
    success: function(response) {
        $("#yourDiv").html(response);
    }
});
</script>
Alex Young
  • 4,009
  • 1
  • 16
  • 34
KeatsKelleher
  • 10,015
  • 4
  • 45
  • 52
6
    document.getElementById("id").innerHTML='<object type="text/html" data="x.html"></object>';
john p
  • 132
  • 1
  • 4
1

There was a way to achieve this in the past, but it was removed from the specification, and subsequently, from browsers as well (e.g. Chrome removed it in Chrome 70). It was called HTML imports and it originally was part of the web components specs.

Currently folks are working on a replacement for this obviously lacking platform feature, which will be called HTML modules. Here's the explainer, and here's the Chrome platform status for this feature. There is no milestone specified yet as of when this feature will land.

Chances are the syntax is going to look similar to this:

import { content } from "file.html";

Resolving the remaining issues with HTML modules I assume might take quite some time, so until then the only viable options you have is to have

We already have JSON modules and CSS module scripts (which both were sorely missing features for a long time as well).

connexo
  • 53,704
  • 14
  • 91
  • 128
  • And whilst we wait for HTML Modules. Take inspiration from [the ```` Web Component](https://dev.to/dannyengelman/load-file-web-component-add-external-content-to-the-dom-1nd) – Danny '365CSI' Engelman Sep 16 '22 at 14:20
  • @Danny'365CSI'Engelman Thank you, but I'm not really interested in any third-party code, whatsoever. I prefer to rely on the platform only, and until then, on my build stack. – connexo Sep 16 '22 at 16:08
-1

http://www.boutell.com/newfaq/creating/include.html

this would explain how to write your own clientsideinlcude but jQuery is a lot, A LOT easier option ... plus you will gain a lot more by using jQuery anyways

drusnov
  • 363
  • 1
  • 8
  • Although this could be a comment, instead answer, is true that jQuery can handle a lot of things. Including getting file contents async. – Máxima Alekz Apr 21 '21 at 19:08