'Adding external js script to next js
In my next project I need to add some script external js files. Like so:
<script src="assets/js/productFactory.js"></script>
I saw one post that said to use Next/Head but this would be contrary to usual practice since many js files get loaded at the bottom of the page.
I tried including it as an import in _app.js like so:
import '../public/plugins/jquery/jquery-1.12.4.min.js';
But this gave me an error.
Any ideas how I should do this?
Solution 1:[1]
in your _document.js
, add script below <NextScript />
tag
<body>
<Main />
<NextScript />
<script src="assets/js/productFactory.js"></script>
</body>
Solution 2:[2]
You can use "useEffect" to achieve this.
useEffect(() => {
const script = document.createElement('script');
script.src = "https://script.js";
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | iamhuynq |
Solution 2 | Jobajuba |