Optimizing JavaScript Performance with Dynamic Imports
Techniques for using dynamic imports to load JavaScript modules on demand, improving application performance and reducing initial load times.
0 likes
9 views
Rule Content
{ "title": "Optimizing JavaScript Performance with Dynamic Imports", "description": "Techniques for using dynamic imports to load JavaScript modules on demand, improving application performance and reducing initial load times.", "category": "JavaScript Cursor Rules", "rules": [ { "id": "dynamic-imports-usage", "description": "Use dynamic imports to load non-essential JavaScript modules only when they are needed, reducing the initial load time of the application.", "examples": [ { "bad": "import { heavyFunction } from './heavyModule';\n\nfunction handleClick() {\n heavyFunction();\n}", "good": "function handleClick() {\n import('./heavyModule').then(({ heavyFunction }) => {\n heavyFunction();\n });\n}" } ] }, { "id": "route-based-code-splitting", "description": "Implement route-based code splitting to load JavaScript code specific to each route, enhancing performance by loading only the necessary code for the current page.", "examples": [ { "bad": "import HomePage from './HomePage';\nimport AboutPage from './AboutPage';\n\nconst routes = [\n { path: '/', component: HomePage },\n { path: '/about', component: AboutPage }\n];", "good": "const routes = [\n { path: '/', component: () => import('./HomePage') },\n { path: '/about', component: () => import('./AboutPage') }\n];" } ] }, { "id": "component-based-lazy-loading", "description": "Use component-based lazy loading to defer the loading of heavy components until they are rendered, improving the initial load time of the application.", "examples": [ { "bad": "import HeavyComponent from './HeavyComponent';\n\nfunction App() {\n return <HeavyComponent />;\n}", "good": "const HeavyComponent = React.lazy(() => import('./HeavyComponent'));\n\nfunction App() {\n return (\n <React.Suspense fallback={<div>Loading...</div>}>\n <HeavyComponent />\n </React.Suspense>\n );\n}" } ] }, { "id": "prefetching-preloading", "description": "Utilize prefetching and preloading techniques to load resources in advance, reducing the time users spend waiting for new content to load.", "examples": [ { "bad": "<link rel=\"stylesheet\" href=\"styles.css\">", "good": "<link rel=\"preload\" href=\"styles.css\" as=\"style\">" }, { "bad": "import('./module').then(module => {\n module.default();\n});", "good": "import(/* webpackPrefetch: true */ './module').then(module => {\n module.default();\n});" } ] }, { "id": "tree-shaking", "description": "Ensure that your code is structured to allow tree shaking, eliminating dead code and reducing the overall bundle size.", "examples": [ { "bad": "module.exports = { unusedFunction, usedFunction };", "good": "export const usedFunction = () => { /*...*/ };" } ] } ] }