I am creating a web component using native implementation, which in it\'s html template has links to images. However, those links only work if they are absolute, or relative
The webcomponent specification defines that URLs are always relative to the main document. This, of course, breaks web component encapsulation, as you rightly concluded. In other words, the specification is buggy, and lots of people are complaining about it. That's why the polyfill doesn't follow the specification: it's fixing the problem.
The specification will change. However, since this is not trivial to fix, it could still take some time. Please see these links:
• https://lists.w3.org/Archives/Public/public-webapps/2014OctDec/0013.html
• https://www.w3.org/Bugs/Public/show_bug.cgi?id=20976#c8
For the moment, the solution is for your component to change the URL of its template images, from relative to absolute. You can get the templateBaseUrl as follows:
(function (window, document)
{
var proto = Object.create(HTMLElement.prototype);
var template = document.currentScript.ownerDocument.querySelector("template");
var templateBaseUrl = template.baseURI;
proto.createdCallback = function ()
{
// Now find all images inside the template and change their src attribute,
// using templateBaseUrl. Also you must change CSS background-image: url(...);
...
};
document.registerElement('test-element', {prototype: proto});
})(window, document);
Another way of fixing this, in case of small images like icons, is to embed the image data directly into the document, with data URIs. This also saves HTTP Requests (until we have Http/2). For example: