Code Monkey home page Code Monkey logo

partytown's Introduction

@nuxtjs/partytown

npm version npm downloads Github Actions CI Codecov License

Partytown integration for Nuxt

Features

  • ๐Ÿ‘Œ Zero-config required
  • ๐Ÿ”ฅ Relocates resource intensive scripts into a web worker
  • โšก๏ธ Speeds up your site
  • ๐Ÿ’ฏ Nuxt 3 and Nuxt Bridge support

Quick setup

  1. Install @nuxtjs/partytown!

    npx nuxi@latest module add partytown
  2. Add it to the modules section of nuxt.config.ts

    export default defineNuxtConfig({
      modules: ['@nuxtjs/partytown'],
    })
  3. Add type: 'text/partytown' attribute to any scripts you want to be handled by partytown.

    <template>
      <div>
        <Script type="text/partytown" src="https://example.com/analytics.js" />
      </div>
    </template>

Configuration

Partytown supports a number of options, which you can pass in your nuxt.config.ts file:

export default defineNuxtConfig({
  // ...
  partytown: {
    /**
     * When `true`, Partytown scripts are not minified. See https://partytown.builder.io/configuration
     * on how to enable more logging.
     *
     * @default true in development
     */
    debug: boolean
    /**
     * Path (relative to your base URL) where the Partytown library should be served from.
     *
     * @default '~partytown'
     */
    lib: string
    // For other options, see https://partytown.builder.io/configuration
  },
})

Example Configurations

Crisp

export default defineNuxtConfig({
  modules: ['@nuxtjs/partytown'],
  partytown: {
    forward: ['$crisp', '$crisp.push'],
  },
  app: {
    head: {
      script: [
        // Insert your CRISP Script here e.g.:
        { innerHTML: 'window.$crisp = []; window.CRISP_WEBSITE_ID = "0000"' },
        { src: 'https://client.crisp.chat/l.js', async: true, type: 'text/partytown' },
      ],
    },
  },
})

Google Tag Manager

export default defineNuxtConfig({
  modules: ['@nuxtjs/partytown'],
  partytown: {
    forward: ['dataLayer.push'],
  },
  app: {
    head: {
      script: [
        // Insert your Google Tag Manager Script here
        { src: '-', async: true, type: 'text/partytown' },
      ],
    },
  },
})

Plausible Analytics

export default defineNuxtConfig({
  modules: ['@nuxtjs/partytown'],
  partytown: {
    forward: ['$plausible', '$plausible.push'],
  },
  app: {
    head: {
      script: [
        { innerHTML: 'window.$plausible = [];' },
        // Update this
        {
          src: 'https://plausible.io/js/script.js',
          defer: true,
          type: 'text/partytown',
          'data-domain': 'your-domains',
        },
      ],
    },
  },
})

Development

  • Run yarn prepare to generate type stubs.
  • Use yarn dev to start playground in development mode.

Licence

MIT Licence

partytown's People

Contributors

ahmadqwer avatar atinux avatar danielroe avatar intevel avatar mannil avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

partytown's Issues

Crisp Chat not showing up

Hi,

Thanks for the work on this plugin. I am trying to integrate Crisp with my Nuxt3 site. Below is my nuxt.config.ts file. I followed the instructions from the README but I am still running into issues. I have a question out with the Crisp team for help as well.

Does Nuxt not do well with third-party chat apps? Almost everything I've tried has not worked. Any help would be appreciated, I'm not even sure where to look for troubleshooting.

Screenshot Capture - 2022-04-27 - 20-53-53

Release with partytown 0.10.0

Latest release for nuxt still has partytown 0.8.0, renovatebot recently merged a commit (552a64e) that bumps the partytown dependency to 0.10.0, can you do a release?

Some functionality such as {preserveBehavior} released in 0.9.x would become available too :)

Vercel cold start nuxt instance error

Config:

partytown: {
    forward: ['$plausible', '$plausible.push', 'dataLayer.push']
  },

  app: {
    head: {
      script: [
        {
          type: 'text/partytown',
          innerHTML: '(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({\'gtm.start\':new Date().getTime(),event:\'gtm.js\'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!=\'dataLayer\'?\'&l=\'+l:\'\';j.async=true;j.src=\'https://www.googletagmanager.com/gtm.js?id=\'+i+dl;f.parentNode.insertBefore(j,f);})(window,document,\'script\',\'dataLayer\',\'GTM-????\');'
        },
        { children: 'window.$plausible = [];' },
        {
          'src': 'https://plausible.io/js/script.js',
          'defer': true,
          'type': 'text/partytown',
          'data-domain': 'domain.com'
        }
      ],
      noscript: [{
        tagPosition: 'bodyOpen',
        innerHTML: '<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-???" height="0" width="0" style="display:none;visibility:hidden"></iframe>'
      }
      ]
    }

It seems I have issues with Vercel and cold starts. Whenever there is a cold start I get "Nuxt Instance error".

CleanShot 2023-05-11 at 08 30 54

CleanShot 2023-05-11 at 08 31 56

I'm not sure how do debug this. Any suggestions?

Google optimize doesn't work

Hi im trying to implement Google Optimize to nuxt3 using partytown. I've implement script adding new plugin to nuxt3:

export default defineNuxtPlugin((nuxtApp: NuxtApp) => {
  const config = useRuntimeConfig();
  useHead({
    script: [
      {
        src: `https://www.googleoptimize.com/optimize.js?id=${config.optimizeId}`,
        async: true,
        gtm: config.gtmId,
        type: 'text/partytown',
      }
    ],
  });
});

I see that script is loading properly:

<script src="https://www.googleoptimize.com/optimize.js?id=OPT-MMSMPHJ" async="true" type="text/partytown-x" gtm="GTM-W57WWW2"></script>

you can check, that the code above is generated here: https://qa.lendi.pl/

I've also tried to set forwarding by adding this to nuxt.config:

  partytown: {
    debug: true,
    logScriptExecution: true,
    logStackTraces: true,
    forward: ['google_optimize', 'google_tag_manager',],
  }

But unfortunately my optimize experiments does not work. When I change script type from text/partytown to text/javascript everything works fine

support csp

Hi โœ‹
We are using CSP in our Nuxt project and use it to block executing inline scripts.
But this module is injecting inline scripts to the head causing bugs.

Do you have an idea what can I do or how much time takes to update the module?use plugins instead of inline scripts.

Nuxt 2 + Bridge "Cannot read property 'publicAssets' of undefined"

I got an error while running partytown on Nuxt 2 (with Bridge)
What I missed?

Package.json

{
"name": "test",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxi dev",
"build": "nuxi build",
"start": "nuxi preview"
},
"dependencies": {
"@nuxtjs/partytown": "^1.1.1",
"core-js": "^3.19.3",
"nuxt-edge": "latest",
"vue": "^2.6.14",
"vue-server-renderer": "^2.6.14",
"vue-template-compiler": "^2.6.14",
"webpack": "^4.46.0"
},
"devDependencies": {
"@nuxt/bridge": "npm:@nuxt/bridge-edge"
}
}

nuxt.config.js
import { defineNuxtConfig } from "@nuxt/bridge";
import PartyTownModule from "@nuxtjs/partytown";

export default defineNuxtConfig({
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: "test",
htmlAttrs: {
lang: "en",
},
meta: [
{ charset: "utf-8" },
{ name: "viewport", content: "width=device-width, initial-scale=1" },
{ hid: "description", name: "description", content: "" },
{ name: "format-detection", content: "telephone=no" },
],
link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }],
},

// Global CSS: https://go.nuxtjs.dev/config-css
css: [],

// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [],

// Auto import components: https://go.nuxtjs.dev/config-components
components: true,

// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [],

// Modules: https://go.nuxtjs.dev/config-modules
modules: [PartyTownModule],
meta: {
script: [{ src: "/test-script.js", type: "text/partytown" }],
},
// partytown: {
// //
// },

// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
});

image

@nuxt/parytown did now work with nuxt 3 for adding gtm, crisp

Hi, I tried to add gtm but the codes did not work:
I followed the complete docs:

export default defineNuxtConfig({
  modules: ["@nuxtjs/partytown"],
  partytown: {
    forward: ["dataLayer.push"],
  },

  devtools: { enabled: true },
  app: {
    head: {
      script: [
        {
          hid: "gtm",
          innerHTML: `window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-QE3C9S378L');`,
        },
        {
          src: "https://www.googletagmanager.com/gtag/js?id=G-QE3C9S378L",
          defer: true,
          type: "text/partytown",
        },
      ],
    },
  },
});

2: crisp:

export default defineNuxtConfig({
  modules: ['@nuxtjs/partytown'],
  partytown: {
    forward: ['$crisp', '$crisp.push'],
  },
  app: {
    head: {
      script: [
        // Insert your CRISP Script here e.g.:
        { innerHTML: 'window.$crisp = []; window.CRISP_WEBSITE_ID = "0000"' },
        { src: 'https://client.crisp.chat/l.js', async: true, type: 'text/partytown' },
      ],
    },
  },
})

Unable to view structured markup and GTM in debug mode

Hi, I tried deploying partytown with our laravel website. I added Google analytics code inline and added datalayer.push in forwards. I managed to remove the CORS error by adding GA inline but now after deploying partytown in production, I am unable to view GTM events in debug mode. Neither am I able to view which events are getting fired and the structured markup has also disappeared from the pages. Please help ๐Ÿฅฒ
Here is my Partytown config:
<script> partytown = { forward: ['dataLayer.push', 'gtag'], }; </script>
My GTM Script:
<script type="text/partytown">(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-XXXXX'); </script>
Here is my google analytics script:

<!-- Google Analytics Code -->
        <script type="text/partytown">
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','http://lexample.com/js/google-analytics.js','ga');

            ga('create', 'UA-XXXXX-1', 'auto');
            ga('send', 'pageview');
        </script>
        <!-- End Google Analytics Code -->

Rewrite nuxt config in runtime

Plugin works like a charm, but for supporting GTM debug i need to stop pushing gtm to partytown if debug enabled which i made based on query parameter, but also i need to stop forwarding dataLayer.push to partytown if debug enabled, what will be proper way to change nuxt config in middleware or plugin?

Thanks

GTM with partytown does not work

I'm trying to use Google Tag Manager with Partytown and Nuxt 3.

  • It works when I disable Partytown, so GTM + GA is configured correctly. I see all event and stuff pop up
  • Nothing happens when I enable Partytown. No Events in GTM, nothing in GA, dataLayer empty

nuxt.config.js

import { defineNuxtConfig } from 'nuxt';

export default defineNuxtConfig({
    modules: [
        '@nuxtjs/partytown',
    ],

    partytown: { forward: ['dataLayer.push'] },

    app: {
        head: {
            script: [
                {
                    children: `
                        (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
                        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
                        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
                        'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
                        })(window,document,'script','dataLayer','GTM-XXXXXX');
                    `,
                    type: 'text/partytown',
                },
            ],
        },
    },
});

I then use window.dataLayer.push({ event: 'pageView' }) --> nothing happens
I see that partytown correctly adds the scripts with text/partytown-x to head

I've tried another head implementation:

script: [
    {
        children: `
            window.dataLayer = window.dataLayer || [];
        `,
    },
    {
        src: 'https://www.googletagmanager.com/gtm.js?id=GTM-P6KLMD5',
        async: true,
        type: 'text/partytown',

    },
],

Both versions work, as long as I disable text/partytown. As soon as I enable partytown, It seems nothing is happening at all. I know that the GTM Debugger seems not to work with Partytown, but I don't see anything happen, also not in GA.

I've set things up according to this docs and your readme (which is incomplete on gtm)

I can't figure out what is wrong as partytown should be more or less a "drop-in", not requiring further config.

Uses deprecated APIs

Google Page Insight score is 92/100 due to the following error Event.path is deprecated and will be removed. Please use Event.composedPath() instead.

I can see this has been fixed on Build.IO's Github (Link Below), but hasn't been implemented into the Nuxt version.

BuilderIO/partytown#328

Is there a possible work around for now , any and all help would be appreciated.

Thank you.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): update dependency @builder.io/partytown to v0.10.2
  • chore(deps): update devdependency @nuxt/eslint-config to v0.3.10
  • chore(deps): update devdependency bumpp to v9.4.1
  • chore(deps): update nuxt core (@nuxt/kit, @nuxt/schema, @nuxt/test-utils, nuxt, vue)
  • chore(deps): update devdependency eslint to v9.1.1
  • chore(deps): update test packages to v1.5.3 (@vitest/coverage-v8, vitest)
  • chore(deps): lock file maintenance

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v4
  • actions/setup-node v4
  • codecov/codecov-action v4
.github/workflows/release.yml
  • actions/checkout v4
  • actions/setup-node v4
npm
package.json
  • @builder.io/partytown ^0.10.0
  • @nuxt/kit ^3.11.1
  • knitwork ^1.0.0
  • serve-static ^1.15.0
  • ufo ^1.5.3
  • @nuxt/module-builder 0.6.0
  • @nuxt/schema 3.11.1
  • @nuxt/test-utils 3.12.0
  • @types/serve-static 1.15.7
  • @vitest/coverage-v8 1.4.0
  • bumpp 9.4.0
  • eslint 9.0.0
  • nuxt 3.11.1
  • prettier 3.2.5
  • typescript 5.4.5
  • vitest 1.4.0
  • vue 3.4.21
  • @nuxt/eslint-config 0.3.8
  • @nuxt/schema 3.11.1
  • pnpm 9.0.6
playground/package.json
  • nuxt 3.11.1

  • Check this box to trigger a request for Renovate to run again on this repository

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (:automergeEarlyMondays). Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Example of reverse proxy configuration

Hi

I'm looking to implement Facebook pixel. This requires a reverse proxy. Can this be done with Nitro? If that's the case I was hoping you'd be able to provide an example similar as to how you did with Plausible and GTM.

[Question] Error when nuxt/pwa module is used

Hi and thanks for partytown integration for nuxt!

When I tried to use this module with nuxt2 project (that also has @nuxt/pwa module), sometimes I see 404 error saying that /~partytown/partytown-sandbox-sw.html file couldn't be found. I guess this is because they are both registered at the same root scop, so only one of them is working.

I am a noob at service workers, so I was wandering, maybe you could help to find out how to have both of them? :)

[bug?] Wrong version of partytown is pulled in by npm

I'm baffled, but if I run an npm why on partytown, it looks like the nuxt module pulls in an old version instead of the latest 0.8.0:

@builder.io/[email protected] dev
node_modules/@builder.io/partytown
  @builder.io/partytown@"^0.7.2" from @nuxtjs/[email protected]
  node_modules/@nuxtjs/partytown
    dev @nuxtjs/partytown@"^1.3.0" from the root project

Even though the package.json correctly has ^0.8.0 listed? ๐Ÿค”

$crisp example and other does not work

Hi, very cool feature, but I failed to implement any example, even direct copy - paste...
Nuxt 3, In console log I can see worker, but can't see chat button, also window.$crisp return a strange function instead of the $crisp object, I tried call this function like window.$crisp() -> undefined

Thank you

Error GTM with nuxt 3

Hi ๐Ÿ˜Š I'm trying to implement GTM to nuxt3 using partytown. I've implement script inside nuxt config like below:
app: {
head: {
script: [
{
hid: "gtm",
src: "https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXX",
"data-cookieconsent": "ignore",
innerHTML: (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-XXXXXX'); ,
async: true,
type: "text/partytown",
},
],
noscript: [
{
tagPosition: "bodyOpen",
innerHTML: <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX" height="0" width="0" style="display:none;visibility:hidden"></iframe>,
},
],
}
...
modules: {
...
"@nuxtjs/partytown",
}
...
partytown: {
debug: true,
forward: ["dataLayer.push"],
},

And when I launch yarn dev command i have an error "fetch" inside the console like screenshot:
Screenshot 2023-01-12 alle 09 56 30

Example of how to use this module

Hi Daniel

This module look awesome, and is just what I need as I have multiple third party script running on my site. I am however a bit confused as to how I actually use it with Nuxt 3.

e.g. I have this Crisp Chat module that I'd like to implement. This is the code I get from Crisp. How would I implement such script?

window.$crisp = []
      window.CRISP_WEBSITE_ID = "0000"
      ;(function () {
        d = document
        s = d.createElement("script")
        s.src = "https://client.crisp.chat/l.js"
        s.async = 1
        d.getElementsByTagName("head")[0].appendChild(s)
      })()

@nuxtjs/partytown is not working with nuxt 3

import { defineNuxtConfig } from 'nuxt3'

export default defineNuxtConfig({
  modules: ['@nuxtjs/partytown'],
  partytown: {
    forward: ['$crisp', '$crisp.push'],
    debug: true
  },
  meta: {
    script: [
      // Insert your CRISP Script here e.g.:
      { children: 'window.$crisp = []; window.CRISP_WEBSITE_ID = "0000"' },
      { src: 'https://client.crisp.chat/l.js', async: true, type: 'text/partytown' } 
    ]
  }
})

Worker not getting initialised

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.