Package Exports
- st-lazy
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (st-lazy) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
st-lazy
What is it?
st-lazy is Stencil decorator that allows you to call component method as the user scrolls component into the viewport. On supported browsers (Chrome and chrome based browsers, Firefox and Edge) it uses IntersectionObserver to accomplish this functionality. For Safari and IE it simply falls back to setTimeout. Inspired by st-img
Installing
Just add module to your Stencil project package.json:
npm i st-lazyHow to use it?
It's very simple: you just need to anotate your method with @Lazy and it will be called when host component is scrolled to viewport. Method will be called once - the first time you scroll to component. Additionally you need to pass host's @Element. You can do it in two ways:
Option 1: passing host element with @LazyHost
import { Component, Element } from '@stencil/core';
import { Lazy, LazyHost } from 'st-lazy';
@Component({ tag: 'lazy-component', shadow: true })
export class LazyComponent {
@LazyHost() @Element() host;
@Lazy()
someMethod() { console.log("someMethod was called because user scrolled to LazyComponent"); }
render() { return <div>Hello, World!</div>; }
}Option 2: passing host element manually
import { Component, Element } from '@stencil/core';
import { Lazy } from 'st-lazy';
@Component({ tag: 'lazy-component', shadow: true })
export class LazyComponent {
@Element() host;
@Lazy("host")
someMethod() { console.log("someMethod was called because user scrolled to LazyComponent"); }
render() { return <div>Hello, World!</div>; }
}When use it?
Basically you can think of every action that you would normally do in componentWillLoad. Maybe some of those actions are time consuming, generating not needed network traffic and not giving any benefit to most of users? Good example is calling an API to get data to be presented by component. Maybe most of users are not even checking some forgotten carousel on the bottom of every page in your app?
Example
Following component
import { Component, State, Element } from '@stencil/core';
import { Lazy, LazyHost } from 'st-lazy';
@Component({
tag: 'test-st-lazy'
})
export class TestStLazy {
@State() name: string;
@LazyHost() @Element() host;
@Lazy()
getName() {
console.log("fetching user data...");
setTimeout(() => {
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(res => res.json())
.then(data => {
this.name = data.name
console.log(this.name);
})
}, 300);
}
render() {
return (
<div><p>Hello {this.name}</p></div>
);
}
}...on the page
<body>
<div style="height: 1000px"></div>
<test-st-lazy></test-st-lazy>
</body>gives
