Only one instance of the Next.js inline script is loaded

Incorporating Tiny Slider into my Next.js application has been a success, but I am facing an issue with the inline script that controls the slider's behavior. The script loads correctly when I first launch index.js. However, if I navigate to another page using Link and return to index.js, the script fails to load.

Here is the code snippet for the script in index.js:

 {/* Script */}
        <Script id='tester'>
          {`
            var slider = tns({
              container: '.my-slider',
              items: 6,
              autoplay: true,
              autoplayTimeout: 2000,
              gutter: 20,
              autoplayButtonOutput: false,
              controls: false,
              navPosition: 'bottom',
              nav: false,
              mouseDrag: true,
              arrowKeys: true,
              responsive: {
                300: {
                  items: 2,
                  gutter: 50,
                  center: true,
                  fixedWidth: 250,
                },
                700: {
                  items: 3,
                  gutter: 50,
                  center: true,
                  fixedWidth: 250,
                },
                1440: {
                  items: 3,
                  gutter: 50,
                  fixedWidth: 250,
                  center: true,
                }
              }
            });
          `}
        </Script>

I'm looking for a solution to ensure that the script loads every time index.js is accessed, not just on the initial visit. Any suggestions on how I can achieve this? You can find the complete code here - https://github.com/YaddyVirus/Esttheva

Answer №1

Learn how to implement tiny-slider in a next.js application with these simple steps.

  1. Create a new file named pages/_document.js to handle the styles loading
// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html>
      <Head>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.2/tiny-slider.css" />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}
  1. Below is an example page showcasing the implementation of the slider
import { useEffect, useRef } from "react";

const App = () => {
  const ref = useRef(true);

  useEffect(() => {
    let slider;
    // Ensure tiny-slider is loaded client-side and only once
    if (typeof window !== "undefined" && ref.current) {
      ref.current = false;
      // Lazy load the slider code client side
      import("tiny-slider").then((x) => {
        slider = x.tns({
          container: ".slider",
          items: 3,
          slideBy: "page",
          autoplay: true
        });
      });
    }
    // Destroy the slider when unmounted
    return slider?.destroy();
  }, []);

  return (
    <div>
      <div className="slider">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
        <div>6</div>
      </div>
    </div>
  );
};

export default App;

Code sandbox link for reference: https://codesandbox.io/s/tina-slider-nextjs-0z8zi6?file=/pages/index.js:0-806

Key points to note about this solution:

  • The ref variable keeps track of whether the hook has been called to prevent duplicates
  • We use
    typeof window !== "undefined"
    to load tiny-slider only on the client-side and avoid server-side errors
  • The tns function is invoked as per the documentation

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

React Native buttons are displaying at a fixed width and not adjusting as expected

Within a row, I have two buttons with a padding of 20 between them, and they are only taking up the necessary width for the button text. The width remains constant! Here is the code for the buttons: <View style={styles.buttonContainer}> &l ...

Click outside of this popup to dismiss it

I have been struggling to figure out how to make this popup close when clicking outside of it. Currently, it only closes when clicked directly on it. Your assistance in this matter is greatly appreciated. Here is the HTML code: <h2>Popup</h2> ...

"Comparison: Java Installation vs. Enabling Java in Your Web Browser

Is there a method to determine if Java is currently running on your system or if it has been disabled in your browser? Our application relies on Java applets, and we typically use "deployJava.js" to load the applet. However, even when Java is disabled in t ...

Utilizing Angular: Importing Scripts in index.html and Implementing Them in Components

Currently, I am attempting to integrate the Spotify SDK into an Angular application. While I have successfully imported the script from the CDN in index.html, I am encountering difficulties in utilizing it at the component level. It seems like there may be ...

Unable to establish proper functionality of username variables in Node.js chat application

For my latest project, I am developing a chat application in node.js following a tutorial from socket.io. The main objective of the app is to allow users to input their username along with a message, which will then be displayed as "username: message" in t ...

Leveraging the outcome of a for loop in order to set a condition within an else if statement

How can I condition my third else if statement based on the result of a for loop? //If player clicks centre on first move go in corner square if (current[4] === playerToken && this.state.stepNumber === 1) { let move = c ...

Receiving a PNG image in the response of a REST call from ServiceNow, the data appears to be garbled with junk characters

I encountered an interesting situation where I received a PNG image as a response from a REST call in ServiceNow. The response seems to be filled with junk characters, making it difficult to work with as shown below. My goal is to write a server script tha ...

Error 500: An invalid data type was encountered in an express.js node.js environment

Currently, I am in the process of developing an Authentication page using a combination of node.js, express.js, and mysql2. The user ID and password entered on the webpage are then passed through app.post('/login',...). However, upon submitting t ...

Maximizing the potential of Angular forms through native FormData

Currently, I am revisiting an older project that still uses traditional methods for form submission. The HTML includes a form element with defined method and action. My goal is to submit the form in the old-fashioned way using the action attribute to post ...

I am looking to implement a dropdown menu that appears after clicking on an image. Any suggestions on how to achieve this using

I've been experimenting with adding a dropdown class, but I'm feeling a bit lost on where to start. Here's a snippet of code that shows what I'd like to do to add a dropdown menu: <span id="dropdown-info" ng-init= "myVar='i ...

Placing a user's username within an ejs template using express and node.js

Currently, I am attempting to integrate the username into a layout using ejs templating with node and express. Below are the steps I have taken: Mongodb model: const mongoose = require('mongoose') const Schema = mongoose.Schema; var uniqueValid ...

The troubleshooting of debugging javascript remotely on IntelliJ with the JetBrains Chrome extension is proving to be unsuccessful

I've been attempting to set up a debugger for some JavaScript files that I'm working on in IntelliJ (version 2020.1.4). Following the guidelines provided here Debug with JetBrains Chrome extension, I believe I have successfully completed all the ...

Adding dynamic metadata to a specific page in a next.js app using the router

I was unable to find the necessary information in the documentation, so I decided to seek help here. My goal is to include metadata for my blog posts, but I am struggling to figure out how to do that. Below is a shortened version of my articles/[slug]/page ...

Is there a way to verify and send notifications when duplicate entries are added to my table?

Whenever a make and model are added using the "add" button, I need to ensure that there are no duplicates. If a duplicate is found, an alert should be displayed, and the entry should not be added to the table. Unfortunately, I have been unable to find a so ...

The async and await functions do not necessarily wait for one another

I am working with Typescript and have the following code: import sql = require("mssql"); const config: sql.config = {.... } const connect = async() => { return new Promise((resolve, reject) => { new sql.ConnectionPool(config).connect((e ...

Utilizing array iteration to display images

I am having trouble getting the images to display on my card component. The description appears fine, but the images are not rendering properly even though I have the image data in an array. Here is the Card Component code: export const Card = (props) =&g ...

Unique bullets for page navigation in Swiper.js/react

I've been attempting to implement custom paginations for my component in order to have bullets outside the container, but unfortunately they are not showing up in the DOM. Below is the code snippet of the component: export function CommentSlider({ co ...

Maintain dropdown menu visibility while navigating

I'm having an issue with my dropdown menu. It keeps sliding up when I try to navigate under the sub menu. I've spent all day trying to fix it, testing out various examples from the internet but so far, no luck. Any help would be greatly apprecia ...

Detach an item from its parent once it has been added to an array

Currently, I am facing an issue with a form on my blog. The blog is represented as an object that contains multiple content objects within it. I seem to be experiencing some confusion because the reactivity of the content I add to the Array persists with t ...

Is it possible to exchange CSS classes for a specific group of elements using JQuery?

I have two list items listed below: <li name="luxury" class="cars luxury> <div id="featured_lux" name="featured" class="carImg_lux col2_lux "> My Luxury Car<img border="0" class="car-im ...