I am using webcomponents.js to polyfill Firefox support of web components.
When loading an HTML template through an HTML import, a script within the template does not execute once the custom-element based on the template is added to the DOM of the main page.
It does execute when running the site in Chrome (which has native web components support).
However, both Firefox and Chrome execute such script when the template is placed within the main page itself.
See the example from Eric Bidelmann at HTML5Rocks. This runs both in Chrome and in Firefox (via webcomponents.js) - as long as the template is located in the same HTML file.
<!DOCTYPE html>
<html>
<body>
<button onclick="useIt()">Use me</button>
<div id="container"></div>
<script>
function useIt() {
var content = document.querySelector('template').content;
// Update something in the template DOM.
var span = content.querySelector('span');
span.textContent = parseInt(span.textContent) + 1;
document.querySelector('#container').appendChild(
document.importNode(content, true));
}
</script>
<template>
<div>Template used: <span>0</span></div>
<script>alert('Thanks!')</script>
</template>
</body>
</html>
But while the template text shows, it does NOT run when loading the template and its content via a HTML import link. As mentioned, it loads the content, but isn't executing the script in Firefox.
Is this a bug in webcomponents.js, or a bug in Firefox? Anyone having a good idea for workarounds (other than "use Polymer or Angular")?
Note - this is based on using Firefox 43 and Chrome 47.
It is not a bug in Firefox, Internet Explorer 11 has the same behaviour (with webcomponents.js).
The importNode
method is not polyfilled by webcomponents.js. That's why <script>
elements are not activated when they are imported.
There an issue opened related to that problem.
My workaround: I don't insert scripts tags <script>
inside an imported <template>
(JS/HTML separated:).
Also, you could parse your <template>
looking for <script>
tags and try to activate/execute them manually (could be somewhat tricky...)