Lazy loading is about reducing the repetitive branching judgment of the code on the external environment, to improve the performance of code execution. The lazy loading mode is not part of the generally defined category of 23
design patterns, but is usually considered as a broadly skilled design pattern.
Lazy loading is achieved by redefining the object to shield the branching judgments in the original object. Our implementation approach is also very simple. Since a certain external environment is certain and no longer needs to be judged, as long as the environment is judged, redefine this method to only return the code logic under a specific branch.
Lazy loading has a wide range of applications, especially in today's diverse browser types. Many functions are implemented differently in different browsers, leading to bloated and redundant code with numerous branching judgments for different browsers, such as event handling and the creation of XMLHttpRequest
objects. Lazy loading can solve this problem and improve code execution efficiency.
For the above requirements, we have two ways to improve:
Two implementation approaches of lazy loading are provided for different browser event registration methods.
When the JavaScript
file is loaded, the method is redefined through closure execution, which consumes some resources when the page is loaded.
When the function is executed for the first time, it is explicitly rewritten inside the function, and the last call completes the first method call. Unlike loading on execution, after the JavaScript
file is loaded, the lazily executed function has not been redefined yet. It is only when the function is called for the first time that it is redefined. Both lazy loading methods avoid redundant branching judgments.