Sunday, 10 January 2016

Include a HTML File

This morning I turned on my laptop intending to quickly fill up my timesheet for the week and bugger off. However, my nerdiness toke over. I decided to improve on my work cheatsheet HTML file.

My cheatsheet is simply a static HTML file that I use as my default web page of my web browser. In the cheatsheet I put all the useful and frequently used links and information. I recently rewrote it using Javascript to dynamically update the URLs depending on whether I am on the company VPN or not. So now I have two versions of it - the new one with Javascript; and the old one in pure HTML, which has way more info than the new one. I am too lazy to migrate everything to the new one so I decided to somehow include it instead.

Since the cheatsheet is a static HTML file only, there is no web server where I can utilise the web container for including another file - e.g. the include tag in ASP/JSP or Apache web server's SSI feature... I can only rely on native HTML or Javascript.

With this constraint, I can think of basically the following approaches:
1. use iframe and this is tried and true, and simple enough to use:

<iframe src='index.htm' style="height:100%; width=100%" />
2. use XMLHttpRequest and set the xhr.responeType to "document":
        if (window.XMLHttpRequest) xhr = new XMLHttpRequest();
        else xhr = new ActiveXObject("Microsoft.XMLHTTP");
        xhr.open("GET", "file://c:/work/index.htm", true);
        xhr.responseType="document";
        xhr.onload=function(e){
            var doc=e.target.response;
            var container=document.body;
            container.appendChild(doc.querySelector('.h'));
        }    
        xhr.send();
3. use HTML5's import feature:
    if('import' in document.createElement('link')) {
        var link=document.createElement('link');
        link.rel="import";
        link.href="index.htm";
        link.onload=function(e) {
            var doc=link.import.querySelector('.h');          
            document.body.appendChild(doc.cloneNode(true));    
        };
        document.head.appendChild(link);   
    } 

Among the above methods, my preference would be HTML5, XHR and iframe, in that order. Unfortunately, XHR and HTML5 import don't allow file:// to be accessed for security reasons. So the only option left is iframe and it works well.

No comments: