Search code examples
javascripthtmldomweb-componenthtml5-template

What is "document.currentScript" and "ownerDocument"?


I am learning Web Components. To grab a template, I needed to do this:

<template>
  <div>The sky is blue</div>
</template>

<script>
    var tmpl = (document.currentScript||document._currentScript).ownerDocument.querySelector('template');

Instead of:

var tmpl = document.querySelector('template');

I don't understand this part at all: (document.currentScript||document._currentScript).ownerDocument

What is currentScript, what is ownerDocument? What is the purpose? Why does it work. Note that the template code I have shown above gets pulled in via the link element.

Note, this is related to this post and this article. I AM just trying to understand the keywords, I don't have any particular problem in mind.


Solution

  • Definition taken from here: https://html.spec.whatwg.org/multipage/dom.html#dom-document-currentscript

    document.currentScript

    Returns the script element, or the SVG script element, that is currently executing, as long as the element represents a classic script. In the case of reentrant script execution, returns the one that most recently started executing amongst those that have not yet finished executing.

    Returns null if the Document is not currently executing a script or SVG script element (e.g., because the running script is an event handler, or a timeout), or if the currently executing script or SVG script element represents a module script.

    And I believe that _currentScript comes from a Polyfill.

    The ownerDocument for anything in the DOM Tree will be document but for a <template> or a file loaded through an HTML Import the ownerDocument will be a different document. This is why document.querySelector() won't work to get the <template> of a file loaded using an HTML Import.