Angad
Angad

Reputation: 2823

Injecting a Polymer web-component into head with JavaScript's appendChild

I'm trying to use JS to load a web-component in a page that let's me plugin my code, but not modify the <head>'s contents.

<script type="text/javascript">
  var script = document.createElement("script");
  script.src = "https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.23/webcomponents-lite.min.js";

  var link = document.createElement("link");
  link.rel = "import";
  link.href = "https://my-cdn.com/build/my-widget.html";

  [script, link].forEach(function(element) {
    document.head.appendChild(element);
  });
</script>

However, this throws the following errors while adding the script tag itself:

webcomponents-lite.min.js:12 Uncaught TypeError: window.wrap is not a function(…)`

A plain HTML page with the equivalent script and link tags inside head work just fine! Any idea how I can accomplish this? The page does pre-load jQuery, so I'm able to use jQuery if needed - but this seemed fairly trivial to me, so have attempted a pure-JS solution.

Upvotes: 2

Views: 579

Answers (1)

Supersharp
Supersharp

Reputation: 31219

Indeed if the error is due to a conflict with another global wrap, it's annoying :-(

Maybe you could try one of these solutions:

  • Undefine the wrap variable just before appending the <script>: var wrap = undefined, but maybe it's not a good idea to redefine it if it's expected elsewhere ;
  • Use another equivalent polyfill: https://github.com/WebReflection/document-register-element ;
  • Rename the window.wrap function in the current polyfill. It's easier that one could imagine (11 ocurrences, that you can rename to wrap2).

Upvotes: 1

Related Questions