Jose A Jose A - 1 month ago 5
Javascript Question

Intercepting HTML imports

I can't find anything around the web. I'm using Polymer 1.6, and I'm trying to do Lazy Loading of the elements. So far I've succeeded in Lazy Loading them and speed has increased considerably.

I'm doing the App Shell architecture, in which I bundle (through minification and vulcanization) all the scripts that are needed for navbar and drawer work.
But, as soon as I do that, there are many HTML imports that are part of the App Shell, that will be called because they differ in name.

I could remove the HTML imports from my elements, but that would be error prone. Note: I know that HTML imports are only executed once, but since they are part of a bundle the browser does not know how to prevent its load.

So what I want to do is to intercept HTML imports, check if the element is part of the App Shell, and prevent its load if it already exists.

Something like this:

var appShellComponents : [

document.addEventListener('HTMLImportEvent', function(event){
//Untested code below
var href = event.srcTarget.href;
var component = href.substr(href.lastIndexOf('/').replace('.html','');
if(appShellComponents.indexOf(component) > -1){
//Element has been loaded, reject the import.


I also need a way to do it with other browsers such as Firefox. Apparently Polymer uses a polyfill that invokes AJAX instead.


The best way is to process the files at the server-side, with a program like gulp or grunt for example.

You could replace the attribute rel='import' of the <link> elements with your own custom name, for example rel='import2', and then process them with your own module loader in the browser.

If you want to handle the links at runtime on the client side, you could wait for the onload event on link (or the HTMLImportsLoaded on document), but I guess these events are fired too late for what you want to achieve (in fact it depends on how the different Web Components are designed).

However with the polyfill (for Firefox and Internet Explorer), it could be possible, because you can patch the code which realizes the XMLHttpRequest calls. Unfortunately it won't work for Chrome and Opera because the <link> are parsed and processed natively and the <script> in the imported files are executed immediately when they are downloaded.

A workaround could be to move the Web Components in a folder so that they won't be found with the initial relative href URL (or use a <base> element with a wrong url). Then you'll just have to insert good <link> when needed.