Search code examples
htmlimportsafariweb-componentpolyfills

How to use HTML imports in Safari with web components.js


I just recently came upon web components and I find it awesome. Nevertheless, it is still not implemented in all browsers. For that reason i'm using webcomponents.js in Safari to be able to use HTML imports. There are several articles and tutorials on how to use the polyfills, but I still find the available documentation lacking. In my case, I'm creating a visual style guide and need to be able to reuse certain bits of code many times all over the guide. I believe that HTML imports could help me in achieving my goal, but once I load webcomponents.js I don't know how to proceed. Notice that at this point I'm not trying to create my own web components, just use imports to load certain HTML bits into certain locations in my visual guide.

This is an example code I'm using:

window.addEventListener('HTMLImportsLoaded', function (e) {
    "use strict";

    var links,
        i,
        content;

    links = document.querySelectorAll('link[rel="import"]'); // I have more than one link tag

    for (i = 0; i < links.length; i += 1) {
        content = links[i].import;
        alert(content); //This shows **null**
    }
});

Notice that when debugging I can see that links is a list of links and that it has all the expected properties (including import), but they are null.

This is how my HTML source looks like:

<div id="outerdiv">
    <div id="innerdiv">
        <header>
            <input id="inputfield" class="textinput" type="text">
            <span id="messagespan">You have notifications</span>
            <label id="snolabel"><input id="snocheck" type="checkbox"> New only</label>
            <link rel="import" href="main-menu.html"/>
            <ul id="menu">
                <li id="reloadbutton">Reload All</li>
                <li id="settingsbutton">Settings</li>
            </ul>
        </header>
        <section id="section-repos">
            <h4>Repositories</h4>
            <link rel="import" href="repo-listing.html"/>
        </section>
    </div>
</div>

Notice that there are two <link rel="import"> tags in use here. The referenced files are in the same folder, so there is no problem with the path being wrong.

Once I'm able to load the referenced files I intend to substitute the relevant <link> tags with the actual HTML code. It can be done differently, but that's not the main concern.

Any help will be appreciated. Thanks for reading.


Solution

  • Well, as it happens often, there is nothing wrong with webcomponents.js or Safari. It turns out that the visual guide boilerplate resolves the path to the files starting with the root of the site, so I had to change all the paths to reflect this fact. Now it is working properly.

    Thanks to the SO community anyway, for being there.