Skip to content

Flexible script loading for Nextjs #4901

@barrysteyn

Description

@barrysteyn

Flexible script loading for Nextjs

Problem

By default, Next will load all the scripts on a page. This could be undesirable for the following reasons:

  1. Performance — some scripts could only be loaded when needed, or loaded after the page load event (especially for things like _error, if you know it is not needed immediately).
  2. Preloading — It is not uncommon to need to run a script — or load a script from a URL — before allowing your Next app to load.
  3. Polyfil preloading — This is the most common application of the previous point. Next bundles some polyfills, but only the ones NEXT requires — which may not be the ones you require. For example, if you require IntersectionObserver, it is on you to load it yourself. Since this is a HUGE polyfill (7kb minzipped!), you do not want to deliver it to all clients — only the ones that absolutely require it (IE <= 11, Safari ALL).

Solution

Instead of immediately rendering page scripts, rather insert the script information into a preloader script that will give hooks that can solve the problems. This became such an issue for us that we created our own component. We spent some time making it production ready... So I suppose this is a feature request with an example of the component that we would want. Our hope is that @timneutkens likes this approach and would consider putting it into Next.

See our code here

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions