Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Code Splitting and Lazy Loading

Code Splitting and Lazy Loading

Optimize bundle size with code splitting and lazy loading

PerformanceOptimizationReactWebpack
by Community
⭐0Stars
👁️13Views
📋1Copies
.antigravity
# Code Splitting Optimization for Google Antigravity

Implement advanced code splitting techniques in your Google Antigravity projects to dramatically improve load times and user experience. This guide covers dynamic imports, route-based splitting, and component-level optimization.

## Dynamic Import Fundamentals

Set up dynamic imports with loading states:

```typescript
// src/components/DynamicLoader.tsx
import dynamic from "next/dynamic";
import { ComponentType, ReactNode } from "react";

interface LoadingProps {
  message?: string;
}

function DefaultLoader({ message = "Loading..." }: LoadingProps) {
  return (
    <div className="flex items-center justify-center p-8">
      <div className="flex flex-col items-center gap-4">
        <div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />
        <p className="text-gray-400 text-sm">{message}</p>
      </div>
    </div>
  );
}

interface DynamicLoaderOptions {
  loading?: ComponentType<LoadingProps>;
  ssr?: boolean;
  loadingMessage?: string;
}

export function createDynamicComponent<P extends object>(
  importFn: () => Promise<{ default: ComponentType<P> }>,
  options: DynamicLoaderOptions = {}
) {
  const { loading: LoadingComponent = DefaultLoader, ssr = true, loadingMessage } = options;
  
  return dynamic(importFn, {
    loading: () => <LoadingComponent message={loadingMessage} />,
    ssr,
  });
}

// Usage examples
export const DynamicChart = createDynamicComponent(
  () => import("@/components/Charts/AreaChart"),
  { loadingMessage: "Loading chart...", ssr: false }
);

export const DynamicEditor = createDynamicComponent(
  () => import("@/components/Editor/CodeEditor"),
  { loadingMessage: "Loading editor...", ssr: false }
);

export const DynamicDataTable = createDynamicComponent(
  () => import("@/components/DataTable/DataTable"),
  { loadingMessage: "Loading data..." }
);
```

## Route-Based Code Splitting

Implement intelligent route prefetching:

```typescript
// src/lib/routePrefetch.ts
import { useRouter } from "next/navigation";
import { useEffect, useCallback } from "react";

interface PrefetchConfig {
  routes: string[];
  delay?: number;
  priority?: "high" | "low";
}

export function useRoutePrefetch({ routes, delay = 2000, priority = "low" }: PrefetchConfig) {
  const router = useRouter();
  
  useEffect(() => {
    const timer = setTimeout(() => {
      routes.forEach((route) => {
        router.prefetch(route);
      });
    }, delay);
    
    return () => clearTimeout(timer);
  }, [routes, delay, router]);
}

export function useLinkPrefetch() {
  const router = useRouter();
  
  const handleMouseEnter = useCallback(
    (href: string) => {
      router.prefetch(href);
    },
    [router]
  );
  
  return { handleMouseEnter };
}

// Smart prefetch based on viewport
export function useIntersectionPrefetch(href: string) {
  const router = useRouter();
  
  const prefetchRef = useCallback(
    (node: HTMLElement | null) => {
      if (!node) return;
      
      const observer = new IntersectionObserver(
        (entries) => {
          entries.forEach((entry) => {
            if (entry.isIntersecting) {
              router.prefetch(href);
              observer.disconnect();
            }
          });
        },
        { rootMargin: "200px" }
      );
      
      observer.observe(node);
      
      return () => observer.disconnect();
    },
    [href, router]
  );
  
  return prefetchRef;
}
```

## Component-Level Splitting

Split heavy components intelligently:

```typescript
// src/components/Dashboard/Dashboard.tsx
"use client";

import { Suspense, lazy, useState } from "react";

// Lazy load dashboard widgets
const AnalyticsWidget = lazy(() => import("./widgets/AnalyticsWidget"));
const RevenueChart = lazy(() => import("./widgets/RevenueChart"));
const UserActivity = lazy(() => import("./widgets/UserActivity"));
const NotificationPanel = lazy(() => import("./widgets/NotificationPanel"));

function WidgetSkeleton() {
  return (
    <div className="bg-gray-800 rounded-xl p-6 animate-pulse">
      <div className="h-4 bg-gray-700 rounded w-1/3 mb-4" />
      <div className="h-32 bg-gray-700 rounded" />
    </div>
  );
}

export function Dashboard() {
  const [activeTab, setActiveTab] = useState<"overview" | "analytics" | "users">("overview");
  
  return (
    <div className="space-y-6">
      <nav className="flex gap-4 border-b border-gray-800 pb-4">
        {(["overview", "analytics", "users"] as const).map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`px-4 py-2 rounded-lg transition-colors ${
              activeTab === tab
                ? "bg-indigo-500 text-white"
                : "text-gray-400 hover:text-white"
            }`}
          >
            {tab.charAt(0).toUpperCase() + tab.slice(1)}
          </button>
        ))}
      </nav>
      
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {activeTab === "overview" && (
          <>
            <Suspense fallback={<WidgetSkeleton />}>
              <AnalyticsWidget />
            </Suspense>
            <Suspense fallback={<WidgetSkeleton />}>
              <RevenueChart />
            </Suspense>
            <Suspense fallback={<WidgetSkeleton />}>
              <NotificationPanel />
            </Suspense>
          </>
        )}
        
        {activeTab === "analytics" && (
          <div className="col-span-full">
            <Suspense fallback={<WidgetSkeleton />}>
              <RevenueChart fullWidth />
            </Suspense>
          </div>
        )}
        
        {activeTab === "users" && (
          <div className="col-span-full">
            <Suspense fallback={<WidgetSkeleton />}>
              <UserActivity />
            </Suspense>
          </div>
        )}
      </div>
    </div>
  );
}
```

## Bundle Analysis and Optimization

Analyze and optimize bundle sizes:

```typescript
// next.config.js
const withBundleAnalyzer = require("@next/bundle-analyzer")({
  enabled: process.env.ANALYZE === "true",
});

module.exports = withBundleAnalyzer({
  experimental: {
    optimizePackageImports: [
      "lodash",
      "date-fns",
      "@heroicons/react",
      "lucide-react",
    ],
  },
  
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.optimization.splitChunks = {
        chunks: "all",
        cacheGroups: {
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name: "vendors",
            chunks: "all",
          },
          common: {
            minChunks: 2,
            priority: -10,
            reuseExistingChunk: true,
          },
        },
      };
    }
    return config;
  },
});
```

Google Antigravity automatically generates optimized code splitting patterns that reduce initial bundle size and improve Time to Interactive for your applications.

When to Use This Prompt

This Performance prompt is ideal for developers working on:

  • Performance applications requiring modern best practices and optimal performance
  • Projects that need production-ready Performance code with proper error handling
  • Teams looking to standardize their performance development workflow
  • Developers wanting to learn industry-standard Performance patterns and techniques

By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their performance implementations.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the Performance code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this Performance prompt commercially?

Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.

Which AI assistants work best with this prompt?

This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.

How do I customize this prompt for my specific needs?

You can modify the prompt by adding specific requirements, constraints, or preferences. For Performance projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...