These examples use Polymer and the ES6 Module Loader polyfill.
Let's say we have an element <foo-baz>
which contains the below button. In this page, we also have a (currently) unknown <polymer-cat>
element we would like to load on-demand.
Click the import button above to dynamically import polymer-cat.html
.
Here we are using Polymer.import
to import our element as follows:
// Signature: Polymer.import(urls, callback) Polymer.import( ['polymer-cat.html'], function() { // called when our import is fully loaded // including any assets like CSS. });
This loads import dynamically and asynchronously. The callback is called when the imports have loaded and any associated polymer-elements have upgraded.
We can similarly Polymer.import
a <polymer-ui-tabs> element, which has many of it's own HTML import dependencies. The tabs will fall back to rendering content as part of a HTMLUnknownElement
until we import the element by clicking on the button below:
Note: Should you need it, a helper mechanism for loading imports is available in the form of HTMLImports.whenImportsReady(callback)
. This is called when the imports in the document at call time have completed loading.
Imagine we have <div id="foo">
and a Polymer element <foo-bar>
. <div id="foo">
has no joy, unless we dynamically load "utils.js" successfully:
When you click the <foo-bar>
dynamically loads "utils.js" and injects the updated text into "foo" with help from our exported contains()
function.
Here we're just using the System.import
method from our ES6 Module Loader to import the "utils" module as follows:
System.import('utils').then(function(module) { var foo = document.getElementById("foo"); var msg = 'the foo has joy'; foo.innerHTML = msg + '. Does it contains() foo?..' + module.contains(msg, 'foo'); });
We can also use System.import
in a <foo-barbaz>
element to dynamically load "utils.js" and then register our Polymer element once resolved. If this works, foo2 should be happy:
The code for this is defined as follows:
System.import('utils').then(function(module) { Polymer('foo-barbaz', { ready: function() { var foo = document.getElementById("foo2"); var msg = 'the foo2 has joy'; foo.innerHTML = msg + '. Does it contains() foo2?..' + module.contains(msg, 'foo2'); } }); });