score:41
this works to me:
create a folder for your static files:
<root>/static/hello.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>
)
hope this help,
regards
score:0
i wrote an article elaborating on this question, hopefully it comes in handy:
https://www.devtwins.com/blog/how-to-add-a-third-party-script-to-a-nextjs-website
score:1
this is what i tried and it worked for me.
i used two files entry-script.js
and main-script.js
. i put these like this
<root>/static/entry-script.js
and <root>/static/main-script.js
the content of entry-script.js
is below.
(function (d, t) {
t = d.createelement("script");
t.setattribute("src", "/static/main-script.js");
d.getelementsbytagname("head")[0].appendchild(t);
})(document);
and the main logic is in the file main-script.js
.
in the file _doucment.js
of nextjs i included my file entry-script.js
in body like below
class mydocument extends document {
render() {
return (
<html>
<head>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=roboto:300,400,500,700&display=swap"
/>
</head>
<body>
<script
type="text/javascript"
src="/static/entry-script.js"
></script>
<main />
<nextscript />
</body>
</html>
);
}
}
export default mydocument;
mydocument.getinitialprops = async (ctx) => {
// resolution order
//
// on the server:
// 1. app.getinitialprops
// 2. page.getinitialprops
// 3. document.getinitialprops
// 4. app.render
// 5. page.render
// 6. document.render
//
// on the server with error:
// 1. document.getinitialprops
// 2. app.render
// 3. page.render
// 4. document.render
//
// on the client
// 1. app.getinitialprops
// 2. page.getinitialprops
// 3. app.render
// 4. page.render
// render app and page and get the context of the page with collected side effects.
const sheets = new serverstylesheets();
const originalrenderpage = ctx.renderpage;
ctx.renderpage = () =>
originalrenderpage({
enhanceapp: (app) => (props) => sheets.collect(<app {...props} />),
});
const initialprops = await document.getinitialprops(ctx);
return {
...initialprops,
// styles fragment is rendered after the app and page rendering finish.
styles: [
...react.children.toarray(initialprops.styles),
sheets.getstyleelement(),
],
};
};
score:4
may this helps you nextjs public folder
move your static folder into public folder in your root directory
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>
...
</head>
<myawesomecomponent />
</div>
)
score:6
with next.js v11, you can use the next component script
https://nextjs.org/blog/next-11#script-optimization
<script
src="..."
strategy="beforeinteractive"
/>
score:19
you can also run js code this
<script
dangerouslysetinnerhtml={{
__html: `
let a = 1;
functioncall();
`,
}}
></script>
score:23
with the below approach you can easily put a script file's raw script text into a generated next.js html page's <head>
without screwing around with character escaping, formatting and general pretending that we aren't actually just building an html page in the end anyways.
there are many use cases you may want a script to run without going to network. ex: 3rd party scripts, monitoring / analytics scripts that expect to be in the <head>
without a separate network load. many of these come minified, mangled, you-name-it and are just supposed to be copy, paste, move on with life.
next.js makes this very hard pretending that everything with web development is magically react and webpack all the time now (i wish right?)
the best developer experience way i've found is to do this:
_document.js
...
<head>
<script type="text/javascript" dangerouslysetinnerhtml={{ __html: process.env.rawjsfromfile }}></script>
</head>
...
next.config.js
https://github.com/vercel/next.js/blob/canary/packages/next/next-server/server/config.ts#l33
module.exports = {
env: {
rawjsfromfile: fs.readfilesync('./rawjsfromfile.js').tostring()
}
}
rawjsfromfile.js
alert('freedom!!!!!!!!!!!!!!!');
// and other 3rd party script junk, heck even minified js is fine too if you need
hope this saves someone from hours of frustration that i endured coming up with this... ðŸ˜
Source: stackoverflow.com
Related Query
- Next.js Loads <script> tags but it doesn't execute them
- Next JS is loading external script but not executing them
- React Helmet only loads script on index page but not on other pages
- I am doing a chrome extension with react but it refuses to execute inline script
- script tag inject but not execute on React
- Visual Studio: Auto complete HTML tags inside an embedded babel script
- React native Refresh works but next call still uses the last token
- Dynamically insert script tag that will execute via Reactjs
- WebRTC getting Failed to execute 'addIceCandidate' on RTCPeerConnection error on console but can still display remote and local videos
- How to execute npm script using grunt-run?
- npm install succeeds but npm run start fails to find both rimraf and react-scripts despite them being installed
- react helmet not showing meta tags in view page source but shows in element on inspect
- How to precisely control where script tag is inserted using Next Script
- Next js initial page loading time is too slow compared to subsequent page loads
- why javascript not wait for and of forEach and execute next line
- Helmet causing MERN app hosted on heroku cause ERROR: Refused to execute inline script because it violates the following
- Chrome Extension: Refused to execute inline script, but no inline scripts present?
- Next JS - Meta Tags Missing in Source Code
- Call a Python script from React with next routing and a node.js server
- My link to manifest.json in index.html works when I run react script 'yarn start', but not when I run 'python3 manage.py runserver'
- next js image component error "url" parameter is valid but upstream response is invalid
- React CRA with CSP: Refused to execute inline script
- how to use fresh state inside the useeffect, but execute cleanup on unmount only
- Next Js Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined
- Delaying react component load until helmet head script loads
- I have 2 states, but both are updating even though I only setState one of them
- Define styles inside component but do not inline them [React]
- Splitting Styled-Components into multiple files but export them as one file
- React Link tag changes the url but doesnt render the component
- I need to execute a function that will update the state right after using setState hook, but state inside function is empty?
More Query from same tag
- How to use material-ui IconMenu inside cell of React fixed-data-table
- React Redux how to get value in to my input
- Gutenberg React - Struggling to use withSelect
- How to pass json into fabric ui dropdown component?
- How dispaly an svg on the option of select with ReactJs?
- 500 internal server error on request to Node server from React client
- generate many components from an array
- ESLint respecting VS Code jsconfig.json baseUrl and paths
- Making site multi language support using google translate for React js
- How do I change route onSubmit in a searchbar?
- How to prevent componentWillReceiveProps to render for every setState here?
- Function overloading with typescript on a react component?
- Populate a ReactJS input field as an end user
- Check username or phone already exist (front)
- Why doesn't `this.state.text = "text"` in a constructor work in ReactJS?
- Component does not rerender in react when changing tab item
- React componentWillUpdate runs every second and condition not working
- browserify-shim Sortable global not being recognized by react-sortable-mixin
- Unable to show Menu item by clicking on the icon using Reactjs
- Disable scroll but without hiding the scroll bar for React JS?
- Where to keep active user data on React + Redux client application
- getServerSideProps not working in nextjs error in mapping
- Upload image using react to active storage rails
- Should the action or store be responsible for transforming data when using React + Flux?
- React firebase auth() setState not working inside then()
- How to exclude special characters from a Textfield in React Hooks Form 7.0
- React Native Expo StackNavigator overlaps Notification bar
- React Context with Multiple State Values not updating initial values
- firebase signOut() method doesn't sign out
- HTMLInputElement forwardRef doesn't accept name