Search code examples
polymerweb-component

How to programmatically insert a <link rel="import"> in the context of web component?


I'm trying to create a custom component using webcomponents.js only, not the full Polymer library. I have managed to create some, but have a problem with this one. This component is a variant of the HTML<link>tag. Instead of having a valid URL in the href attribute, it has a string that will be processed to produce a valid URL. Example:

<!-- "variable" will be replaced to produce a valid URL -->
<my-link href="http://example.com/{{variable}}.html" >

I process this web component, adding a link in the DOM using a valid URL with a javascript code like:

var link = document.createElement('LINK');
link.rel = "import";
link.href = processMyLinkHref();
this.appendChild(link);

That link is correctly retrieved later with a doc.querySelectorAll('link[rel="import"]');instruction. But the DOM corresponding to the imported file that should be there, and I can get it if I use a regular <link rel="import">tag, is unavailable in the import attribute of the link object.

It looks like that the ressource has not been fetched by the browser. I tried to look in the source of webcomponents.js, found calls to handleImportjavascript functions through closures, but my knowlegde of javascript is not good enough to really understand what goes on here.

So here is the question: how do I make the browser fetch the imported file just like it was a regular HTML <link>?


Solution

  • My javascript knowledge is better now, and I understand the problem. Contrary to what I wrote, the ressource is fetched when the link node is inserted. But it's content is not stored anywhere. You have to do this manually. It's a little bit strange, but...

    The code that works is:

    // Create a new import node
    var importNode = document.createElement('link');
    importNode.href= href;
    importNode.rel= 'import';
    // Set the callback used when import is loaded. The line below is
    // adapted from importHref function in Polymer
    importNode.onload = importLoaded.bind(this, importNode);
    // Triggers import loading
    document.head.appendChild(importNode);
    

    And the callback code is:

    var importLoaded = function (importNode, event) {
        // Put the document DOM tree in the import attribute as usual
        importNode.import = event.target.import;
    };
    

    You can use importHref in your own code, but I wanted to insert a <link rel"import"> code just as if it was written in the page source code directly.