0.0.22 • Published 2 years ago
@terrahq/dyn-import v0.0.22
@terrahq/dyn-import
Javascript library for to improve performance, it is tought to be used on scroll or on click event. This is benefitial when you want to load a modal on click, trigger something on scroll,etc.
It also tought to fire only once if you have multiple elements.
Usage
Install
npm install @terrahq/dyn-import
Import
import DynamicImportEvent from "@terrahq/dyn-import";
Example on Click
let clickDataElements = document.querySelectorAll(".js--trigger-button");
if (clickDataElements) {
clickDataElements.forEach((element, index) => {
let result: any = false;
new DynamicImportEvent({
type: {
fireEvent: "click",
clickElement: element,
},
callback: async () => {
if(!result){
// @ts-ignore
result = import("./modules/Bar.js").then((x) => {
document.querySelectorAll(".js--foo").forEach((element, index) => {
new x.default({ });
});
});
}else{
// Once the class has been initialized, use the funcions of the dynamic imported Class. In this case (InjectContent Class)
result.init()
}
},
});
});
}
Example on Scroll
if (document.querySelector(".js--bar")) {
const FooModuleInstance = new DynamicImportEvent({
type: {
fireEvent: "scroll",
distance: 200,
},
callback:() => {
import("./modules/Foo.js").then((x) => {
document.querySelectorAll(".js--trigger").forEach((element, index) => {
new x.default({
triggerCardElement: element,
});
});
});
},
});
}
Example on Observer
let observerDataElements = document.querySelectorAll(".js--observer-data");
if (observerDataElements) {
observerDataElements.forEach(element => {
let result:any = '';
new DynamicImportEvent({
type: {
fireEvent: "observer",
element: element,
rootMargin : element.getAttribute("data-root")
},
callback: async () => {
// Checks if the import class has been fired
if(!result){
// @ts-ignore
result = await import("./modules/ChangeElement").then((x) => {
return new x.default({
element : element
})
}).catch(()=> console.log('there was a problem'))
}else{
result.init({
element : element
})
}
},
});
});
}
<div class="c--cta-a js--observer-data" data-root="100px">
....
</div>
Options
Option Name | Type | Default | Desc | |
---|---|---|---|---|
fireEvent | string | could be "scroll" or "click", | ||
distance | number | 100 | if "scroll" is defined, it is expected to add how much the user has to scroll from top of the page | |
clickElements | HTMLCollection | if "click" is defined, it is expected to know which triggers are responsable of fire the event. | ||
fireOnce | boolean | true | if "true" the callback will be executed just one time. | |
element | HTMLCollection | if "observer" is defined, it is expected to know which triggers are responsable of fire the event. | ||
rootMargin | string | if "observer" is defined, the html has a data-root attribute use it, else use the 100px default value |
Methods
There is a public method to destroy the class & remove event listeners
FooModuleInstance.destroy();