Optimizing Next.js: Mastering the Art of Handling Scripts for Specific Routes

We're utilizing a chat plugin with GTM in our Next.js application.

Our goal is to have GTM handle everything, without any code on the front end. GTM injects the main script and also handles injecting the init script.

We only want the chat to be visible on specific pages, not all of them.

The issue is that once the script is loaded, it remains loaded.

Currently, it was statically implemented which is why it isn't functioning as expected:

<script>
 window.addEventListener("foo", () => {
    // DO SOMETHING
  });
</script>

Thus, the callback will fire on every page once loaded.

To address this dynamically, I am considering using dynamic variables like so:

<script>
     const enableFoo = {{customGTMVariable}};
</script>
<script>
 enableFoo && window.addEventListener("foo", () => {
    // DO SOMETHING
  });
</script>

Will this method work or should I explore options involving the DataLayer?

While I am not an expert in GTM, our consultants are supposed to be. I want to be well-prepared when discussing this with them to resolve the issue.

Possibly updating a cookie with each page change could help?

The key is to avoid modifying the front-end code. Anything achievable with GTM should suffice.

Answer №1

To solve this issue, follow these steps:

  • Include a new attribute in the dataLayer using GTM
  • Develop a script that is consistently loaded and capable of performing three tasks:
  1. Track changes in the URL
  2. Optimize the document object model (DOM)
  3. Review the dataLayer to determine if the script should be executed

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

Negative outcome resulting from utilizing ng-pattern (Angular.JS) along with unicode characters

Currently, I am implementing an ng-pattern for an input field that should only allow Hebrew characters. I have researched the Unicode numbers for Hebrew characters. This is the pattern I am using: $scope.hebrewCharacterPattern = /[\u05D0-\u05F ...

Get JSON data through AJAX using two different methods

Help needed: JSON request issue with XMLHttpRequest var xhr = new XMLHttpRequest(); function elenco_studenti() { var url = "/controller?action=student_list"; xhr.responseType = 'text'; xhr.open("GET", url, true); xhr.onreadystat ...

"Capturing the essence of the web: Explore the

Hi there! Recently, I came across this fascinating short video at and I can't stop thinking about how to replicate that cool scanning effect. From what I gathered, it seems like you need two groups: one with solid cubes and the other with wireframed ...

In the Kendo AngularJS tree view, prevent the default behavior of allowing parent nodes to be checked

Hi there, I am currently using Kendo treeview with Angularjs. My tree view has checkboxes in a hierarchy as shown below Parent1 Child1 Child2 I would like the functionality to work as follows: Scenario 1: if a user selects Parent1 -> Child1, Chil ...

Building a table in Quasar by utilizing nested objects

I am currently facing an issue while using Quasar to create Q-Tables. I am struggling with incorporating nested objects with dynamic key names. Below is the content of my table: data: [ { 'FrozenYogurt' : { &a ...

The following authentication error occurred: JWEDecryptionFailed - the decryption process has encountered a failure

[...nextauth]/route.js file import { User } from "@/lib/models"; import { connectToDb } from "@/lib/utils"; import NextAuth from "next-auth"; import GitHubProvider from "next-auth/providers/github"; export const aut ...

When using the `display: table-cell` property on a div element, it does not automatically respect

How can I restrict the width of columns by defining a width attribute on the div.dcolumn DOM element to preserve the layout with overflowing cells? I want the content of any overflowing cell (like the 9px column) to be hidden while maintaining the specifie ...

Anticipating the outcome of a function in asynchronous JavaScript

After taking a break from web development for a couple of years, I recently dove back into it. While I dabbled in AngularJS before, I have now shifted my focus to Angular2. My current challenge revolves around handling asynchronous JavaScript. Despite enc ...

Drop the <span> element into a paragraph by utilizing JQuery's drag and drop feature

Trying to drag and drop <span> into <p>. The code is functional, but encountering 3 issues: When editing content inside <p> by typing (e.g. three words) and then dragging <span> into <p>, the newly typed words are consider ...

Obtaining the value of a variable beyond the asynchronous function immediately invoked expression

Having trouble accessing the value of con in other functions despite trying various methods like .thens and awaits from stack articles. Unfortunately, I keep encountering errors stating that con is not valid. Feeling stuck and unsure how to proceed with t ...

Creating an effective follow-following system in Node.js

I have built a Node.js application that features a basic follow system, allowing users to receive the latest articles from those they follow. The current implementation involves creating an array called followers, which stores the userIDs of all users fol ...

Using Javascript and jQuery to convert text into a tag

I'm attempting to use JavaScript to send a message on twitch.tv by modifying the textarea in the chatbox. <textarea class="tw-textarea tw-textarea--no-resize " placeholder="Send message" data-a-target="chat-input" data-test-selector="chat-input" s ...

Deployment of a NextJS14 app to Vercel encountered an issue: Unexpected token '<' found in JSON at position 0

Here is the issue at hand: next: 14.1.4 next-auth: 4.24.7 node version: 20 This is the structure of my authentication folder: No errors occur when running npm run dev I've been investigating this issue for three days, but I am still stuck. I belie ...

Converting TypeScript to JavaScript in a React JS application: Steps and best practices

As a beginner in the world of React, I am currently struggling with transitioning from TypeScript to JavaScript The code snippet below demonstrates the use of table filter with TypeScript. How can I adapt this code to utilize JavaScript instead? Click he ...

I would like to find the difference between two arrays by creating a third array that only contains the elements not found in the first array

Subtracting elements from two arrays. arr1=["AT","IN","UK","US"] and arr2=["UK","ZA"]. I want the result to be arr1-arr2 = ["AT","IN","US"] I have attempted to perform the subtraction of the arrays as described above, but instead of obtaining the correct ...

The Typescript Decorator is triggered two times

I submitted a bug report regarding Typescript because I suspect there is an issue, although I'm seeking additional insights here as well. This is the scenario. When running the following code: class Person { @IsValueIn(['PETER', ' ...

Implementing the Tab key functionality without redirecting to the address bar

I recently integrated a Tab control into my project, but I'm encountering an issue where pressing the Tab key causes the address bar to jump when I try to press another key. This only happens after the Tab key functions correctly in the scene. How can ...

Running functions with parameters in AngularJS using $timeout: What you need to know

Within my AngularJS controller, I have a function that looks like this; polling_interval=1000; var poll = function() { //Execution code $timeout(poll, polling_interval); }; poll(); This function uses the $timeout service in AngularJS to call itsel ...

What is the best way to smoothly enlarge a div as new content is introduced?

Is there a way to smoothly expand a div when new content is added? const [render, setRender] = useState(false) const showHide= () => { setRender(!render) } return ( <div className="container"> <h1>TEST ...

React-highlightjs failing to highlight syntax code properly

I'm currently using the react-highlight library to highlight code snippets in my next.js application. However, I've encountered an issue with the code highlighting when using the a11y-dark theme. https://i.stack.imgur.com/ip6Ia.png Upon visitin ...