Next.js加载< script>标记,但不会执行 [英] Next.js Loads <script> tags but it doesn't execute them
问题描述
我正在将现有的React应用程序集成到Next.js中,主要用于SEO功能.
I'm integrating an existing React app into Next.js for mainly SEO features.
我将css文件链接粘贴到 Next.js
中的< Header>
标记内,它们似乎工作得很好.当我尝试使用< script>
标记对javascript文件执行相同操作时,它不会在这些脚本内执行代码.但我可以在chrome开发工具中看到它们已加载 http 200
.
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.
我尝试使用来自 npm
的名为 Loadjs
的库将脚本加载到 componentDidMount
内部,但是得到的结果与使用完全相同>< script>
标记.
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.
是否有适当的方法在我不知道的 Next.js
中做这种简单的事情?
is there a proper way to do such simple thing in Next.js
that i'm not aware of ?
这是 pages/index.js
文件中包含的代码.
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/malihu-custom-scrollbar-plugin@3.1.5/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>
)
对不起,您回答的太晚了.原来,我链接的所有 scripts
都错过了一个实际上会为每个操作运行 functions
的脚本.
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.
推荐答案
这对我有用:
为您的静态文件创建一个文件夹:
Create a folder for your static files:
< root>/static/hello.js
在您的index.js中
in your index.js
< root>/pages/index.js
import Head from 'next/head';
import MyAwesomeComponent from '../components/mycomponent';
export default () => (
<div>
<Head>
<script type="text/javascript" src="/static/hello.js"></script>
</Head>
<MyAwesomeComponent />
</div>
)
希望获得帮助,
致谢
这篇关于Next.js加载< script>标记,但不会执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!