Can't find template by id when it's in imported file

461 views Asked by At

I'm creating simple custom element and i would like to import it from separated file. When it's in the same file t is giving right html element, but when it's in outside file it's undefined. Here is my index.html file:

<!DOCTYPE html>  
<html lang="en">  
  <head>
    <meta charset="utf-8">
    <link rel="import" href="example-container.html">
  </head>
  <body>
    <example-container></example-container>
  </body>
</html>

And example-container.html:

<template id="example-container">
    <style>
    </style>
</template>
<script>  
    // Make sure you extend an existing HTMLElement prototype
    var ExampleContainerProto = Object.create(HTMLElement.prototype);

    //var t = document.querySelector('#example-container');

    // Setup optional lifecycle callbacks
    ExampleContainerProto.createdCallback = function() {
        var t = document.querySelector('#example-container');
        console.log(t);
    };
    var ExampleContainer = document.registerElement('example-container', {prototype: ExampleContainerProto});
</script>

My another approach was to define t in the global scope, like this:

var t = document.querySelector('#wizard-container');
WizardContainerProto.createdCallback = function() {
    console.log(t);
...

And it work's fine, but i don't want to leave garbage in the global scope.

1

There are 1 answers

2
Scimonster On

When using imports, the global document object refers to the parent page (index.html), not the imported page (example-container.html). You can get the imported document using document.currentScript.ownerDocument. So, it looks like you're querying the wrong document.

See HTML Imports - #include for the web on HTML5Rocks.