In our code sometimes we need a function to load after some time the page is loaded, for stuff like caching the articles of website which is not needed while the page load is happening.
I was wondering if we can write or use some syntax which can lazy load that particular function.
Example:
lazyload funnction xyz(){
// put your code here
}
If there is any way to do this or something similar approach, It is fine if you point me to any patterns, frameworks etc.
First, you should distinguish between "lazy loading" and "delayed loading".
I'm not sure whether your need is strictly lazy loading. But their implementation is similar enough. This is how I would do it, assuming you don't want to use modules.
Idea: have the lazily-loaded code in a separate file, and load the file by adding a script
tag to your DOM. Then set an arbitrary trigger for this action to achieve delayed loading.
main.js
:function loadDelayed() {
const tag = "<script src='delayed.js'></script>";
document.querySelector("head").insertAdjacentHTML("beforeend", tag);
}
// E.g. trigger via timeout after 5 seconds
setTimeout(loadDelayed, 5000);
delayed.js
:function myDelayedFunc() {
// Your code here
}
If you just want lazy loading, create one .js
file for each lazily-loaded function:
Eg func1.js
:
(() => {
// Your code here
})();
And in main.js
create a helper function:
function runLazy(funcName) {
const tag = `<script src='${funcName}.js'></script>`;
document.querySelector("head").insertAdjacentHTML("beforeend", tag);
}
runLazy("func1");
Note: although the browser will load the file from cache after the first call, this naive approach will always add a new script tag to your DOM every time you call runLazy()
. If you intend to call the function many times, you might wish to use loadDelayed()
and then call the function normally.
You can add a script dynamically using JavaScript:
let script = document.createElement('script');
script.src = "/caching.js";
document.body.append(script);
The script will start loading once it's been added to the document.
Dynamically loaded scripts behave like async
by default, but you can change the order from “First Loaded – First Executed” to the order in which they are appended into the document by explicitly setting the async
property to false
:
let script = document.createElement('script');
script.src = "caching.js";
script.async = false;
document.body.append(script);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.