DEV Community

Marcin Wosinek
Marcin Wosinek

Posted on • Edited on

4 2

webpack 5 - lazy load library in application

Have you ever seen your app load very slow, just because you added a big, 3rd party library? A neat solution for that kind of case, it's to use lazy load - delaying a download of big chunks of code. This approach allows having some part of the application already working, while the rest is being loaded.

non lazy-load

example of application loading a big, pdf before starting the application:

import { PDFDocument } from "pdf-lib"; // synchronous import

// ...

pdfButton.addEventListener("click", async () => { 
  const pdfDoc = await PDFDocument.create();
  const page = pdfDoc.addPage([350, 400]);
  page.moveTo(110, 200);
  page.drawText("Hello World!");
  const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
  document.getElementById("pdf").src = pdfDataUri;
});
Enter fullscreen mode Exit fullscreen mode

lazy load in webpack

import(/* webpackChunkName: "pdf-lib" */ "pdf-lib").then(({ PDFDocument }) => {
  // ..

  pdfButton.addEventListener("click", async () => {
    const pdfDoc = await PDFDocument.create();
    const page = pdfDoc.addPage([350, 400]);
    page.moveTo(110, 200);
    page.drawText("Hello World!");
    const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
    document.getElementById("pdf").src = pdfDataUri;
  });
});
Enter fullscreen mode Exit fullscreen mode

import() is a dynamic import from javascript. Webpack translates "pdf-lib" to a new asset it creates dynamically. /* webpackChunkName: "pdf-lib" */ allow us to name the new asset. When I was removing this line, my lazy-loaded chunk was called 55.js - not the best name if ever somebody would have to troubleshoot some issues around it.

Interested in more?

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free