Tips for minimizing the influence of external code in Next.js

What steps can I take to minimize the impact of third-party code on my next.js app? I have incorporated Google Analytics and Google AdSense on my website, but it is causing performance issues.

view this illustration

_document.js

import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html>
        <Head>
          <script
            defer
            src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_ID}`}
          />
          <script
            defer
            dangerouslySetInnerHTML={{
              __html: `
                                window.dataLayer = window.dataLayer || [];
                                function gtag(){dataLayer.push(arguments);}
                                gtag('js', new Date());
                                gtag('config', '${process.env.GA_ID}', {
                                page_path: window.location.pathname,
                                });
                            `,
            }}
          />
          <script
            defer
            src={
              "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-75************"
            }
            crossOrigin="anonymous"
          ></script>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

Visit my website - click here

Answer №1

Discover the power of the latest Next.js Script tag. Dive into the documentation and unlock the secrets to improved script management.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a variable and set it equal to the value of a form

I'm having trouble setting a value to a hidden form field that needs to come from a query string parameter. The function that extracts the query string parameter is working properly, but the function that assigns this variable to the hidden form field ...

Obtaining the data value from a style applied to a div element in an E-commerce platform like MyShop

I have recently started using MyShop for my online store at www.myshop.com. The programming language they use is quite different from what I am used to. For example, the total price in the basket.html script is displayed using the following code: <spa ...

Identify matching values in objects and dynamically update them with a custom value

I have an array structured like this: var array = [ { dates: "2020-12-25", class: "first" }, { dates: "2020-12-26", class: "last" }, { dates: "2021-06-11", class: "first" }, ...

Updating Angular Material theme variables during the build processIs this okay?

How can I easily customize the primary color of my angular 6 application to be different for development and production builds? Is there a simple solution to automatically change the primary color based on the build? ...

Unexpected changes to JSON payload being caused by Next.js API Route

There seems to be a strange issue occurring when sending JSON formatted data through Postman as raw text. When the exact same data is sent through Postman as raw JSON (the only difference being the content-type header changing from application/text to appl ...

Getting the parameters of a path from the URL's breadcrumb in Vue.js

Currently utilizing Vue Attempting to include path parameters in breadcrumb URLs for my app's router. Looking to achieve something similar to the following: { path: 'pages/gestion/region/:reg', name: 'gestion-depa', ...

How can I set up an additional "alert" for each form when making an AJAX request?

let retrieveLoginPasswords = function (retrieveForgottenPasswords, checkLoginStatus) { $(document).ready(function () { $('#login,#lostpasswordform,#register').submit(function (e) { e.preventDefault(); $.ajax({ type: &quo ...

dynamically import a variety of components in vue.js and nuxt depending on certain conditions

Is there a way to implement dynamic imports for all 3 components in this scenario? Each component has different props, so using the switch option in the computed method is not feasible. I have come across solutions for using a single component dynamically ...

Error: JSON parsing stopped due to unexpected end of file while attempting to parse data

After testing with other APIs successfully, I found that this particular one is not functioning as expected. const express = require("express"); const https = require("https"); const bodyParser = require("body-parser"); const ...

leaflet.js - Place a marker when clicked and update its position while dragging

Currently working on a small project that requires the ability to place a marker on an image-map powered by leaflet.js, and update its position if it's dragged. I was using the code below for this functionality but keep getting an error 'marker n ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

using an external JavaScript function in the MongoDB shell

In my case, I have JavaScript functions that are stored in a JSON file: functions={} functions.a = function(){ return "returned" } I've come across tutorials suggesting that by importing this JSON file, I should be able to use these ...

Activate a change or response when the input value in Javascript is altered

Currently, I am working on a small project using JQuery and facing an issue when trying to remove error classes from HTML elements. To handle the removal of the error classes, I am utilizing $('selector').on('input') event to target th ...

What is the best way to retrieve a value by using the data.get() method?

I am currently facing an issue with retrieving the value of a textarea that I have dynamically added to a fieldset in my form. When I attempt to submit the form, the code below is executed: function handleSubmit(e) { e.preventDefault(); console.log( ...

Error message encountered while trying to instantiate 'FormData'

My contact form was working perfectly fine until recently when it suddenly stopped allowing me to send messages. I keep encountering this error message every time I try to submit the form: Uncaught TypeError: Failed to construct 'FormData': pa ...

Error: Uncaught ReferenceError: d3 is undefined. The script is not properly referenced

Entering the world of web development, I usually find solutions on Stack Overflow. However, this time I'm facing a challenge. I am using Firefox 32 with Firebug as my debugger. The webpage I have locally runs with the following HTML Code <!DOCTYP ...

Guide to changing the checkbox value using JavaScript

Describing the Parent Element: <span style="background: yellow; padding: 50px;" onClick="setCheckBox()"> <span> </span> <input type="checkbox" name="f01" value="100"> </span> ...

A one-page digital space that functions as a dynamic slide show

Check out this cool website I want to emulate. The site is a single-page design where you can navigate vertically using various methods like keyboard, mouse, scroll, or swipe gestures. There are carousels that allow left and right navigation. Each section ...

What is the process for incorporating a node.js module into Next.js?

Can I integrate the pdf2json npm module into my next.js application without using express? I'm attempting to include this code snippet in my next.js app: const fs = require('fs'); const PDFParser = require("pdf2json"); const pdfParser = ne ...

Clear the cache following the service call

I am currently working on a service that has two methods. Utilizing the built-in cache support for $resource, I am trying to implement a way to refresh the cache when a service call is made from the controller. I attempted to use $cacheResource without suc ...