Jump to content

Lazy loading

From Wikipedia, the free encyclopedia

Lazy loading(also known asasynchronous loading) is a technique used incomputer programming,especiallyweb designandweb development,to defer initialization of anobjectuntil it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used. This makes it ideal in use cases wherenetworkcontent is accessed and initialization times are to be kept at a minimum, such as in the case ofweb pages.For example, deferring loading of images on a web page until they are needed for viewing can make the initial display of the web page faster. The opposite of lazy loading iseager loading.[1]

Examples

[edit]

With web frameworks

[edit]

Prior to being established as a web standard,web frameworkswere generally used to implement lazy loading.

One of these isAngular.Since lazy loading decreases bandwidth and subsequently server resources, it is a strong contender to implement in a website, especially in order to improveuser retentionby having less delay when loading the page, which may also improvesearch engine optimization(SEO).[2]

Below is an example of lazy loading being used in Angular, programmed inTypeScriptfromFarata Systems[3]

@NgModule({
imports:[BrowserModule,
RouterModule.forRoot([
{path:'',component:HomeComponent},
{path:'product',component:ProductDetailComponent},

{path:'luxury',loadChildren:()=>import('./luxury.module').then(m=>m.LuxuryModule),data:{preloadme:true}}]
//, {preloadingStrategy: CustomPreloadingStrategy}
)
],
declarations:[AppComponent,HomeComponent,ProductDetailComponent],
providers:[{provide:LocationStrategy,useClass:HashLocationStrategy},CustomPreloadingStrategy],
bootstrap:[AppComponent]
})

As a web standard

[edit]

Since 2020, major web browsers have enabled native handling of lazy loading by default.[4][5]

This allows lazy loading to be incorporated into a webpage by addingHTML attributes.

Theloadingattribute support two values,lazyandeager.[6]Setting the value tolazywill fetch the resource only when it is required (such as when an image scrolls into view when a user scrolls down), while setting it toeager,the default state, the resource will be immediately loaded.

<!-- These resources will be loaded immediately -->
<imgsrc="header_image.jpg">
<imgsrc="header_image2.jpg"loading="eager">

<!-- While these resources will be lazy loaded -->
<imgsrc="article_image.jpg"alt="..."loading="lazy">
<iframesrc="video-player.html"title="..."loading="lazy"></iframe>

Methods

[edit]

There are four common ways of implementing the lazy load design pattern:lazy initialization;avirtual proxy;aghost,and avalue holder.[7]Each has its own advantages and disadvantages.

Lazy initialization

[edit]

With lazy initialization, the object is first set tonull.

Whenever the object is requested, the object is checked, and if it isnull,the object is then immediately created and returned.

For example, lazy loading for a widget can be implemented in theC#programming language as such:

privateint_myWidgetID;
privateWidget_myWidget=null;

publicWidgetMyWidget
{
get
{
if(_myWidget==null)
{
_myWidget=Widget.Load(_myWidgetID);
}

return_myWidget;
}
}

Or alternatively, with thenull-coalescing assignment operator??=

privateint_myWidgetID;
privateWidget_myWidget=null;

publicWidgetMyWidget
{
get=>_myWidget??=Widget.Load(_myWidgetID);
}

This method is the simplest to implement, although ifnullis a legitimate return value, it may be necessary to use a placeholder object to signal that it has not been initialized. If this method is used in amultithreaded application,synchronization must be used to avoidrace conditions.

Virtual proxy

[edit]

A virtual proxy is an object with the same interface as the real object. The first time one of its methods is called it loads the real object and then delegates.

Ghost

[edit]

Aghostis the object that is to be loaded in a partial state. It may initially only contain the object's identifier, but it loads its own data the first time one of its properties is accessed. For example, consider that a user is about to request content via an online form. At the time of creation, the only information available is that content will be accessed, but the specific action and content is unknown.

An example inPHP:

$userData=array(
"UID"=>uniqid(),
"requestTime"=>microtime(true),
"dataType"=>"",
"request"=>""
);

if(isset($_POST['data'])&&$userData){
//...
}

Value holder

[edit]

Avalue holderis a generic object that handles the lazy loading behavior, and appears in place of the object's data fields:

privateValueHolder<Widget>valueHolder;

publicWidgetMyWidget=>valueHolder.GetValue();

See also

[edit]

References

[edit]
  1. ^"What is Lazy Loading | Lazy vs. Eager Loading | Imperva".Learning Center.Retrieved2022-02-02.
  2. ^"What Is Lazy Loading? Understanding Lazy Loading for SEO".
  3. ^Fain, Y., Moiseev, A. (2018). Angular Development with TypeScript, Second Edition. DecemberISBN9781617295348.
  4. ^"A Deep Dive into Native Lazy-Loading for Images and Frames".15 May 2019.
  5. ^"Firefox 75 gets lazy loading support for images and iframes".15 February 2020.
  6. ^"Lazy loading - Web Performance | MDN".developer.mozilla.org.Retrieved2022-03-15.
  7. ^Martin Fowler (2003).Patterns of Enterprise Application Architecture.Addison-Wesley. pp. 200–214.ISBN0-321-12742-0.
[edit]