Nodular Pudding Multiverse

    @charlietango/use-script
    TypeScript icon, indicating that this package has built-in type declarations

    2.3.0 • Public • Published

    useScript

    With useScript you can lazy-load external third party scripts, that your components might depend on. It checks if the requested url already exists and reuses it, instead of creating a new load request.

    Checkout the Storybook demo.

    Installation

    yarn add @charlietango/use-script

    API

    const [ready, status] = useScript(url)

    The hook returns an array, where the first value is a boolean indicating if the script is ready. The second value is the current loading status, that will be one of the ScriptStatus enum values:

    enum ScriptStatus {
      IDLE = 'idle',
      LOADING = 'loading',
      READY = 'loaded',
      ERROR = 'error',
    }

    Example

    import React from 'react'
    import useScript, { ScriptStatus } from '@charlietango/use-script'
    
    const Component = () => {
      const [ready, status] = useScript('https://api.google.com/api.js')
    
      if (status === ScriptStatus.ERROR) {
        return <div>Failed to load Google API</div>
      }
    
      return <div>Google API Ready: {ready}</div>
    }
    
    export default Component

    Keywords

    Install

    npm i @charlietango/use-script

    DownloadsWeekly Downloads

    5,095

    Version

    2.3.0

    License

    MIT

    Unpacked Size

    9.69 kB

    Total Files

    6

    Last publish

    Collaborators

    • thebuilder
    • frederik_bosch