javascripthtmlbrowser

Download javascript dynamically and execute it later


I am trying to optimize page loading time. And the only thing left is optimizing asset loading times. I have few assets and a library script. Some of the assets are dependent to this library.

Vendor Scripts

Bundle Scripts

What I want to achieve is start loading all of these assets when page is fully loaded. As I am rendering everything at serverside, it is not a problem for me to delay user interactions. I just need to download library.min.js then page.bundle.js in the exact order but when I need to.

I tried few things, but I just couldn't start downloading and execute it in right order. Currently I am planning to use xhr and eval content when I need it. But I am not sure if this is the right way. There are more questions to ask when using this method. Caching etc.

Can someone give me an idea how can I split download and execution time of dynamically loaded javascript files?


Solution

  • You can dynamically create script elements and add it to the document body, set the src property to your javascript file and then let it download it. When the download finished, the promise will resolve and the next dependent js file will be set.

    function setExternalScript(src) {
      return new Promise((resolve, reject) => {
           const scriptTag = document.createElement('script');
           scriptTag.type = 'text/javascript';
           scriptTag.src = src;
           scriptTag.onload = () => resolve();
           document.appendChild(document.body, scriptTag);
      });
    }
    
    async function afterLoaded() {
        const scripts = ['a.js','b.js','c.js'];
        for(let i=0; i< scripts.length; i++)
           await setExternalScripts(scripts[i]);
    }
    
    afterLoaded(); // run this whenever you need