Home > Mobile >  Next JS is loading external script but not executing them
Next JS is loading external script but not executing them

Time:06-14

In my next app with the latest version 12.1.6, I'm trying to use bootstrap. I've added bootstrap CSS and js files from CDN to the head of pages/_app.js as below,

import '../styles/globals.css'
import Head from 'next/head';

function MyApp({ Component, pageProps }) {
  return (
      <>
      <Head>
        <meta charset="UTF-8"/>
        <meta name="keywords" content="Ogani, unica, creative, html"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"></meta>
        <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
        </Head>
      <Component {...pageProps} />
      </>
   );
  }

export default MyApp 

I used bootstrap Nav as below,

 <nav >
  <button  type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation">
    <span ></span>
  </button>
  <a  href="#">Navbar</a>

  <div  id="navbarTogglerDemo03">
    <ul >
      <li >
        <a  href="#">Home <span >(current)</span></a>
      </li>
      <li >
        <a  href="#">Link</a>
      </li>
      <li >
        <a  href="#">Disabled</a>
      </li>
    </ul>
    <form >
      <input  type="search" placeholder="Search" aria-label="Search"/>
      <button  type="submit">Search</button>
    </form>
  </div>
</nav>

I've noticed bootstrap CSS is loaded and executing. But its JS is loading but not executing. Because the page isn't interactive menu isn't expanding and collapsing on click. Can anyone tell me what's a problem with it?

CodePudding user response:

import Head from 'next/head';

const Layout = (props) => (
<div>
    <Head>
        {/* import external javascript */}
        <script type="text/javascript" src="..."></script>
        <script type="text/javascript" src="/js/myscript.js"></script>
    </Head>
    <p id="demo"></p>
</div>
);

export default Layout;

CodePudding user response:

The error was occurring because React/Next DOM operations were colliding with Jquery DOM operations. By deferring the jquery operations after react/next it worked. Just used useEffct hook to do jquery. It's solved here.

Replace the IIFE in mainW.js for: // of course you perhaps want better names

function _runJQueryControls($) {
// rest of function
}

window.runJQueryControls = () => _runJQueryControls(jQuery); Inside index.js

 useEffect(() => {
    window?.runJQueryControls();
  }, []);

In next.config.js /** @type {import('next').NextConfig} */

const nextConfig = {
  reactStrictMode: false, 
};

special thanks to icyJoseph who helped.

  • Related