Lazy loading

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search

Lazy loading (also known as asynchronous loading) is a design pattern commonly used in computer programming and mostly in web design and development to defer initialization of an object until the point at which 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 where network content is accessed and initialization times are to be kept at a minimum, such as in the case of web pages. The opposite of lazy loading is eager loading. Lazy Loading is majorly used in images on web to make them appear only when they are needed making the webpages load faster.

Frameworks that use lazy load[edit]

A pretty famous framework that uses lazy load is Angular. There have been some discussions whether lazy load really helps since it increases server communication. Essentially, lazy load helps Angular developers to decide which modules to load at initialization, or when a function is called. It is claimed to support on small devices and internet with low capacity.

Below is an example of lazy loading being used in Angular, programmed using TypeScript from Farata Systems[1]

@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 ]
})

Implementations[edit]

There are four common ways of implementing the lazy load design pattern: lazy initialization; a virtual proxy; a ghost, and a value holder.[2] Each has its own advantages and disadvantages.

Lazy initialization[edit]

With lazy initialization, the object to be lazily loaded is originally set to null, and every request for the object checks for null and creates it "on the fly" before returning it first, as in this C# example:

private int myWidgetID;
private Widget myWidget = null;

public Widget MyWidget
{
    get
    {
        if (myWidget == null)
        {
            myWidget = Widget.Load(myWidgetID);
        }

        return myWidget;
    }
}

Or with the null-coalescing operator '??'

private int myWidgetID;
private Widget myWidget = null;

public Widget MyWidget
{
    get { return myWidget = myWidget ?? Widget.Load(myWidgetID); }
}

This method is the simplest to implement, although if null is 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 a multithreaded application, synchronization must be used to avoid race 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]

A "ghost" is the object that is to be loaded in a partial state. It may 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 all we know is that content will be accessed but what action or content is unknown.

PHP example:

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

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

Value holder[edit]

A value holder is a generic object that handles the lazy loading behavior, and appears in place of the object's data fields:

private ValueHolder<Widget> valueHolder;

public Widget MyWidget => valueHolder.GetValue();

Web Implementation[edit]

Enabling the browser to serve and display pages in the least amount of time is a critical need of today's modern world. The simplest method to implement Lazy Loading is as follows

<img src="image.jpg" alt="..." loading="lazy"> <iframe src="video-player.html" title="..." loading="lazy"></iframe>

The loading attribute support two values, lazy and eager. Eager will load the image on priority while lazy will fetch it only when it is required or the image is in the viewport.

See also[edit]

References[edit]

  1. ^ Fain, Y., Moiseev, A. (2018). Angular Development with TypeScript, Second Edition. December ISBN 9781617295348.
  2. ^ Martin Fowler (2003). Patterns of Enterprise Application Architecture. Addison-Wesley. pp. 200–214. ISBN 0-321-12742-0.

External links[edit]