Share this page 

Include a file into a page (Ajax style)Tag(s): Language Language

With the component Microsoft.XMLHTTP for IE and XMLHttpRequest for Mozilla-based browser to make HTTP request and fetch the response without loading a new page.

Suppose we have an header that we want to include in each page (header.txt)

<h1>Header included</h1>
and footer (footer.txt)
<h2>Footer included</h2>
then to use them in each page we do something like this (includedemo.html)
<TITLE> Include Demo </TITLE>

// new prototype defintion
document.include = function (url) {
 if ('undefined' == typeof(url)) return false;
 var p,rnd;
 if (document.all){
   // For IE, create an ActiveX Object instance
   p = new ActiveXObject("Microsoft.XMLHTTP");
 else {
   // For mozilla, create an instance of XMLHttpRequest.
   p = new XMLHttpRequest();
 // Prevent browsers from caching the included page
 // by appending a random  number (optional)
 rnd = Math.random().toString().substring(2);
 url = url.indexOf('?')>-1 ? url+'&rnd='+rnd : url+'?rnd='+rnd;
 // Open the url and write out the response"GET",url,false);
 document.write( p.responseText );

this the body

Try it here

See also this Howto : Insert a text file into a page.

See also this HowTo : Include an external JS file from another js file or server-side process.