Declaratively import a HTML component when you're ready to use it. Useful for improving the performance of routing in SPAs built on Web Components.
Install lazy-import with Bower (Yarn support coming soon)
$ bower i lazy-import --saveImport it into the <head> of your document
<link rel="import" href="/bower_components/lazy-import/lazy-import.html">lazy-import relies on emerging standards, for full cross-browser support include the Web Components Lite polyfill.
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.24/webcomponents-lite.min.js"></script>Set the path to your element import in the href property, then set active when you want to import it
<lazy-import href="path/to/my-element.html">
<my-element></my-element>
</lazy-import>
<!-- Import and show <my-element> -->
<script>
document.querySelector('lazy-import').active = true;
</script>lazy-import only imports a component once (the first time active is true, or if a new href is set), regardless of how many times active changes. When active is false, lazy-import is set to display: none, so your component is not in the document flow until it is imported.
Use lazy-import with simple content switchers like Polymer's iron-pages to turn them into performant, lazy-loading component routers.
Make your router set the active prop on the active route, and wrap view components in lazy-import. That way both the import and your element will be hidden when inactive, and routing will automatically import the view component lazily
<iron-pages
attr-for-selected="data-route"
selected-attribute="active"
>
<lazy-import data-route="app" href="/path/to/my-app">
<my-app></my-app>
</lazy-import>
<lazy-import data-route="other-view" href="/path/to/other-view">
<other-view></other-view>
</lazy-import>
</iron-pages>| Property | Type | Description |
|---|---|---|
href |
String |
Path to import when active |
active |
Boolean |
Whether to import component and show lazy-import |
activeAttr |
String |
Optional attribute to set on children when active |
loading |
Boolean |
True while an import is being fetched & parsed |
--
MIT © Sean King sean@seanking.org