Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

Thanks in advance, everyone!

like image 837
MapWeb Avatar asked Aug 20 '10 21:08

MapWeb


People also ask

How can I load a page without iframe?

Use the object Tag as an Alternative to Iframe in HTML We can use the object tag in HTML to embed external resources in the webpage. We can use the tag to display another webpage in our webpage. The object tag is an alternative to the iframe tag in HTML.

How do I load an HTML file into a div?

To load external HTML into a <div>, wrap your code inside the load() function. To load a page in div in jQuery, use the load() method.

How do you embed HTML in HTML?

Embedding an HTML file is simple. All we need to do is use the common „<link>“ element. Then we add the value „import“ to the „rel“ attribute. Using „href“ we attach the URL of the HTML file, just like we are used to when it comes to stylesheets and scripts.


1 Answers

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.

like image 72
bobince Avatar answered Oct 11 '22 18:10

bobince