Lazy loading

From SocialStack
Revision as of 14:31, 31 August 2022 by Luke (talk | contribs) (Created page with "Sometimes you'll want to use a large javascript library inline in your project. Inline is usually recommended anyway as it eliminates external dependencies which some projects...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Sometimes you'll want to use a large javascript library inline in your project. Inline is usually recommended anyway as it eliminates external dependencies which some projects don't permit or don't support, such as an app build. But because of its size, it may have a negative impact on page load times. That page load time penalty is even worse if the library itself isn't used frequently, or not at all during the majority of page visits. This is the situation where lazy loading is useful - load a .js file on demand rather than bundling it always.

Avoiding the js file from being bundled

Firstly, the SocialStack UI compiler will collect all .js files in your project and bundle them together. In this case that's not what we want. It can be avoided (this is true for .css files as well) by creating a folder called static and placing your .js library file in there. For example UI/Thing/static/thingLibrary.js.

Loading the file

Next, you'll want to load the file on demand. A simple fetch is often enough, but webRequest does also have a built in convenience function called lazyLoad which has a cache internally to avoid loading the same thing repeatedly. Here's how to use it:

import {lazyLoad} from 'UI/Functions/WebRequest';
import thingLibraryRef from './static/thingLibrary.js';
import getRef from 'UI/Functions/GetRef';

...

// When it comes time to require your library e.g. because some function is called, do this:

lazyLoad(getRef(thingLibraryRef, {url:1})).then(imported => {
    // If the file exported anything, it will be available in imported.
    // Otherwise it may just be in the window scope, i.e. window.thingLibrary.
})