skip to Main Content

Which one is better to use in general? dynamic import with import() statement or script loading function?

they both make network requests, so which one is more performant? Or maybe webpack’s built-in dynamic import() is the best one to use?

example of script loading function:

function loadScript(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.async = true;
    script.src = url;

    script.addEventListener('load', () => {
      resolve(true);
    });

    script.addEventListener('error', (event) => {
      reject(event);
    });

    document.head.appendChild(script);
  });
}

2

Answers


  1. There are pros and cons to both approaches but undoubtfully, When it comes to performance, using the import() statement can be more efficient in terms of code splitting.

    It allows your build tool (e.g., Webpack) to analyze your code and split it into smaller, more manageable chunks that are loaded on-demand. This can result in faster initial page loads and improved resource utilization.

    Its important to keep your project’s browser support requirements. If you need to support older browsers, you may need to use a combination of approaches or polyfills to ensure compatibility.

    Login or Signup to reply.
  2. You mention webpack, because webpack is a bundler import something from "something" will often not even translate into a physical import depending on how the bundler optimises chunks. So in most cases that type of import should be used the majority of the time.

    But import("something").then(..., aka dynamic import really shines when your application becomes large. Let’s say you have a Dashboard, with lots of Widgets, if you used a dynamic import for each widget, you can have something already rendered before, while the widgets are loading, if you used static import all code would be required to load before you could start to show the user anything.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search