UNPKG

@nuxt/scripts

Version:

Load third-party scripts with better performance, privacy and DX in Nuxt Apps.

39 lines (38 loc) 1.39 kB
import { withQuery } from "ufo"; import { useRegistryScript } from "#nuxt-scripts/utils"; import { object, string, optional } from "#nuxt-scripts-validator"; export const GoogleAnalyticsOptions = object({ id: string(), l: optional(string()) }); export function useScriptGoogleAnalytics(_options) { return useRegistryScript(_options?.key || "googleAnalytics", (options) => ({ scriptInput: { src: withQuery("https://www.googletagmanager.com/gtag/js", { id: options?.id, l: options?.l }) }, schema: import.meta.dev ? GoogleAnalyticsOptions : void 0, scriptOptions: { use: () => { const gtag = function(...args) { window["gtag-" + (options.l ?? "dataLayer")](...args); }; return { dataLayer: window[options.l ?? "dataLayer"], gtag }; }, performanceMarkFeature: "nuxt-third-parties-ga", tagPriority: 1 }, clientInit: import.meta.server ? void 0 : () => { const dataLayerName = options?.l ?? "dataLayer"; const dataLayer = window[dataLayerName] || []; window[dataLayerName] = dataLayer; window["gtag-" + dataLayerName] = function() { window[dataLayerName].push(arguments); }; window["gtag-" + dataLayerName]("js", /* @__PURE__ */ new Date()); window["gtag-" + dataLayerName]("config", options?.id); } }), _options); }