10up / wp-scaffold

10up WordPress project scaffold.
MIT License
194 stars 46 forks source link

Build an "Import on Visibility" and "Interaction" Helper #177

Open dainemawer opened 1 year ago

dainemawer commented 1 year ago

Is your enhancement related to a problem? Please describe.

As per the guidance specified in the patterns.dev book released by Addy Osmani, we should look at building a mechanism to allow wp-scaffold to load heavy JS-related elements on interaction (user click, for instance) or on visibility.

Import on Interaction: https://www.patterns.dev/posts/import-on-interaction Import on Visibility: https://www.patterns.dev/posts/import-on-visibility

The two approaches largely tackle different elements:

Import on Interaction: Use Cases

We must update our Babel configuration to support dynamic imports to achieve this. Babel 7.5+ offers this straight out of the box. We will need to double-check if 10up-toolkit leverages this version. If not, and if you do not wish to upgrade to Babel 7.5+ on your project, there is a drop in babel plugin you can use.

const btn = document.querySelector("button");

btn.addEventListener("click", (e) => {
  e.preventDefault();
  import("@components/my-heavy-library")
    .then((module) => module.default)
    .then(executeHeavyLibrary()) // use the imported dependency
    .catch((err) => {
      console.log(err);
    });
});

Import on Visibility: Use Cases

To achieve this functionality, we need to leverage the Intersection Observer API - its a fairly simple API that's well documented on MDN. Each implementation would likely be very different but at a high-level:

let options = {
  root: document.querySelector("#scrollArea"),
  rootMargin: "0px",
  threshold: 1.0,
};

let observer = new IntersectionObserver(callback, options);

callback in this instance is the function that is fired, which could be a dynamic import of functionality.

These methods would help us reduce project bundle size in the long term, thus delivering a smaller pay load to the client (browser)

Designs

N/A

Describe alternatives you've considered

N/A

Code of Conduct

joesnellpdx commented 1 year ago

@dainemawer This is awesome!

Providing guidance / examples in the scaffold will be really helpful!

Also, for any core block references, we may need more specific guidance / recommendations / solutions within the scaffold. Depending on how this moves forward, I could see pulling out the core blocks into a separate issue (or maybe and/or in the gutenberg best practices site)

CC: @fabiankaegy