Search code examples
javascriptreactjsnext.js

Next.js Loads <script> tags but it doesn't execute them


I'm integrating an existing React app into Next.js for mainly SEO features.

i pasted the css files links inside the <Header> tag in Next.js and they seem to work just fine. when i tried to do the same with the javascript files using the <script> tag, it doesn't execute the code inside those scripts. but i can see them loaded with http 200 in the chrome dev tools.

I tried using a library called Loadjs from npm to load the scripts inside componentDidMount but i got the exact same result as using <script> tag.

is there a proper way to do such simple thing in Next.js that i'm not aware of ?

Here's the code included in the pages/index.js file.

  import React from "react"
  import Head from 'next/head'
  import MyAwesomeComponent from "../components/mycomponent.js"
  export default () => (
    <div>
      <Head>

        <link type="text/css" rel="stylesheet" href="static/css/chatwidget.css" />
        <link type="text/css" rel="stylesheet" href="static/css/download.css" />

        <script type="text/javascript" src="static/libs/jquery.min.js"></script>
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/jquery.mCustomScrollbar.concat.min.js"></script>
        <script type="text/javascript" src="static/libs/bootstrap.min.js"></script>
        <script type="text/javascript" src="static/libs/owl.carousel.min.js"></script>
        <script type="text/javascript" src="static/scripts/chatHead.js"></script>
        <script type="text/javascript" src="static/libs/jquery.magnific-popup.js"></script>
      </Head>

      <MyAwesomeComponent /> {/* a simple React component that returns  : <p>Hello World </p>*/}
    </div>
  )

Sorry for the late answer. it turned out that all the scripts i linked missed one script that would actually run the functions for each action.


Solution

  • This works to me:

    Create a folder for your static files:

    <root>/public/static/script.js

    in your index.js at <root>/pages/index.js

    import Head from 'next/head';
    import MyAwesomeComponent from '../components/mycomponent';
    
    export default () => (
      <div>
        <Head>
          <script type="text/javascript" src="/static/script.js"></script>
        </Head>
        <MyAwesomeComponent />
      </div>
    )
    

    Note that static is the name I used in this example, it's not a requirement, it would work with any other folder name.