Load HTML File Contents to Div [without the use of iframes]
Asked Answered
W

8

69

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.

Wiersma answered 20/8, 2010 at 21:35 Comment(2)
If that's the only way of doing it, I guess it would be okay. I've never used jQuery though..Wiersma
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 JavascriptSlacks
L
117

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.

Littlejohn answered 20/8, 2010 at 22:44 Comment(7)
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.Fennelflower
Strange, I get a NS_ERROR_DOM_BAD_URI: Access to restricted URI denied errorSpaetzle
@Costa: sounds like you are trying to do a cross-site XMLHttpRequest. That's disallowed for security reasons, unless the target site opts in.Littlejohn
Today's browsers won't let you XHR onto the filesystem. You will need to set up a test web server.Littlejohn
@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.Roughhouse
@datelligence: if writing <script>x</script> 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 <script> block expects to be at the tail of the parsed DOM.) NB this explanation is trying to rationalise early browser behaviour that probably wasn't deeply-thought through but now can't be changed.Littlejohn
How would you make this work with an external file, such as one loaded from a Nextcloud instance?Refurbish
F
80

jQuery .load() method:

$("#y").load("x.html");
Fleabane answered 20/8, 2010 at 21:51 Comment(5)
jQuery is great and does all things.Latoyalatoye
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.Platitude
@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.Unlace
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.Sitnik
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?Ephebe
D
29

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

Drover answered 17/3, 2019 at 17:18 Comment(2)
+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.Larock
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: #49773482.Erechtheum
P
12

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>
    
Patsypatt answered 2/3, 2021 at 13:32 Comment(3)
Good to see this use of async/await.Priestcraft
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?Drover
@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.Patsypatt
C
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>
Catechumen answered 20/8, 2010 at 21:41 Comment(0)
I
6
    document.getElementById("id").innerHTML='<object type="text/html" data="x.html"></object>';
Impotence answered 1/7, 2016 at 1:58 Comment(0)
A
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).

Acoustician answered 8/8, 2022 at 17:3 Comment(2)
And whilst we wait for HTML Modules. Take inspiration from the <load-file> Web ComponentChoplogic
@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.Acoustician
D
-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

Dyspepsia answered 20/8, 2010 at 21:58 Comment(1)
Although this could be a comment, instead answer, is true that jQuery can handle a lot of things. Including getting file contents async.Manikin

© 2022 - 2024 — McMap. All rights reserved.