Skip to content

[Proposal] We should have mechanism to know that delayed.js is loaded (delay phase has started)  #405

@yugandhar02

Description

@yugandhar02

Problem statement:
The delayed.js library is effective for loading third-party or deferred scripts, but if some block needs to handle things during delay phase, it requires importing block code in delayed.js, leading to code dispersion. For example, if a developer wants to utilize the Video.js library for adaptive streaming, it’s beneficial to render a poster image while deferring script loading to improve the LHS score.

Consider the following scenarios:

  1. The video block is not loaded in the page.
  2. The video block is loaded before delayed.js.
  3. The video block is loaded after delayed.js.

This necessitates writing logic within delayed.js to determine whether Video.js needs to be loaded, resulting in scattered code.

// video-block.js
export function loadVideoJs() {
   // fetch scripts and render video
}

// delayed.js
if (document.querySelector('.video-js')) {
   const { loadVideoJs } = await import("./blocks/video-block.js");
   loadVideoJs()
}

While cases 1 and 2 can be managed with scattered code, case 3 poses a challenge.
To handle case 3, we need some identifier to check if delayed.js is loaded since the script is not added to dom.

Proposal :

  1. set DELAYED_PHASE property in window to handle case 3.
  2. Trigger delayed-phase event once delayed.js is loaded

e.g.

// video-block.js
export function loadVideoJs() {
   // fetch scripts and render video
}

export decorate(block) {
   if (window.DELAYED_PHASE) {
      await loadVideoJs();
   } else {
      document.addEventListener('delayed-phase', loadVideoJs);
   }
}

// delayed.js
document.dispatchEvent(new Event('delayed-phase'));
Window.DELAYED_PHASE = true;

Benefits :

  1. Colocated code for blocks which needs to handle things during delay phase
  2. Easier integration for shared blocks. No documentation is needed to use shared block which relies on delay phase

Customers using video block:
Volvo
Maruti suzuki

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