Skip to content

Hook for scripts being loaded #160

@joachimhviid

Description

@joachimhviid

It would be helpful to be able to react to a script getting loaded. Currently the module has a scripts:updated hook that can be used for searching for the loaded event, but it is will be inefficient to iterate through the events to find the 'loaded' event, every time there is an update.
Instead I propose a scripts:loaded hook that will be called once when the script reaches that status. This allows the developer to react to the specific event and run some logic in response. For instance, you might want to run a consent update or a custom event once a script has been loaded via a consent banner.
An example implementation could look something like the following inside the useScript composable:

head.hooks.hook('script:updated', (ctx) => {
  if (ctx.script.id !== instance.$script.id)
    return
  if (ctx.script.status === 'loaded') {
    nuxtApp.callHook('scripts:loaded', { [ctx.script.id]: true })
  }
  // convert the status to a timestamp
  payload.events.push({
    type: 'status',
    status: ctx.script.status,
    at: Date.now(),
  })
  payload.$script = instance.$script
  syncScripts()
})

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