next-lazy-load-script
is a simple and lightweight library for lazy-loading external scripts in your Next.js applications. It helps improve performance by deferring the loading of non-critical scripts until they are needed.
- Efficiently lazy-load external scripts.
- Works seamlessly with Next.js.
- Easy to use with customizable options.
- Supports modern JavaScript and TypeScript.
npm install next-lazy-load-script
# or
yarn add next-lazy-load-script
'use client';
import { ScriptStatus, useScript } from 'next-lazy-load-script';
import { useEffect } from 'react';
const TweetScriptLoader = ({ url }: { url: string }) => {
const scriptStatus = useScript({
src: 'https://platform.twitter.com/widgets.js',
defer: true,
});
useEffect(() => {
if (scriptStatus === ScriptStatus.READY) {
window.twttr.widgets.load();
}
}, [scriptStatus, url]);
return <></>;
};
export default TweetScriptLoader;
Prop | Type | Description |
---|---|---|
url | string | Required. The URL of the script to load. |
defer | boolean | Optional. If true, the script is deferred. Defaults to false. |
async | boolean | Optional. If true, the script is asynchronously. Defaults to false. |
attributes | {key: string, value: string}[] | Optional. Attributes to set with the script dom. |
- Enhance page speed by loading scripts only when needed.
- Avoid blocking the rendering of critical resources.
- Simplify script management in your Next.js projects.