Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@valu/lazy-script

Package Overview
Dependencies
Maintainers
2
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@valu/lazy-script

Lazy load 3rd party scripts

  • 0.3.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
2
Created
Source

Lazy Load 3rd Party Scripts

The smart way.

Install

npm install @valu/lazy-script

Usage

Learn by example:

import { LazyScript } from "@valu/lazy-script";

const SCRIPT = new LazyScript({
    // URL to the script to be loaded
    src: "https://finmun.boost.ai/chatPanel/chatPanel.js",

    // Initialization code to be executed only once when the script was loaded
    initialize: () => {
        if (typeof window.boostChatPanel !== "function") {
            throw new Error("window.boostChatPanel not configured properly");
        }

        const chatPanel = window.boostChatPanel({
            apiUrlBase: "https://finmun.boost.ai/api",
        });

        return chatPanel;
    },
});

Lazily bind event handlers:

SCRIPT.lazy((chatPanel) => {
    chatPanel.addEventListener("chatPanelClosed", () => {
        alert("Chat closed");
    });
});

Load the code immediately:

document.querySelector("button").addEventListener("click", () => {
    SCRIPT.now((chatPanel) => {
        chatPanel.show();
    });
});

Things to note:

  • Calling .now() triggers all previous and future .lazy() bindings
  • Calling .lazy() alone does not do anything
  • Calling .now() multiple times is ok. The script will be loaded only once and the initialization script is executed only once too
  • The callbacks will get the return value of the initialize function

Events

Listen to script load events with

const unbind = SCRIPT.onStateChange(() => {
    console.log(SCRIPT.state); // "pending" | "loading"  | "ready"
});

This can be used to implement loading indicators.

React

There's a React hook for easy access to the script state from render:

import { useLazyScript } from "@valu/lazy-script/react";

function Component() {
    const state = useLazyScript(SCRIPT);
}

FAQs

Package last updated on 15 Dec 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc