nuxt-gtag
Version:
Natively integrates Google Tag into Nuxt
33 lines (32 loc) • 846 B
JavaScript
import { defineNuxtPlugin, useHead, useRuntimeConfig } from "#imports";
import { withQuery } from "ufo";
import { initGtag, resolveTags } from "./utils.js";
export default defineNuxtPlugin({
parallel: true,
setup() {
const options = useRuntimeConfig().public.gtag;
const tags = resolveTags(options);
if (!tags.length)
return;
initGtag({ tags });
if (options.initMode === "manual")
return;
const strategy = options.loadingStrategy === "async" ? "async" : "defer";
useHead({
link: [
{
rel: "preload",
as: "script",
href: withQuery(options.url, { id: tags[0]?.id })
}
],
script: [
{
"src": withQuery(options.url, { id: tags[0]?.id }),
[strategy]: true,
"data-gtag": ""
}
]
});
}
});