Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Mix Preload Laravel Package

spatie/laravel-mix-preload

Laravel package that adds a @preload Blade directive to automatically output preload/prefetch tags from your mix-manifest.json. Mark chunks by including “preload” or “prefetch” in the filename to optimize asset loading.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-mix-preload
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Spatie\MixPreload\MixPreloadServiceProvider"
    
  2. First Use Case: Add @preload directive to your Blade template's <head> section:

    <head>
        @preload
    </head>
    
  3. Configure Mix Manifest: Ensure your mix-manifest.json includes chunk names prefixed with preload- or prefetch-:

    {
        "/js/preload-heavy-library.js": "/js/preload-heavy-library.js",
        "/css/prefetch-next-page.css": "/css/prefetch-next-page.css"
    }
    
  4. Verify Output: The directive will auto-generate <link> tags for preload/prefetch based on the manifest.


Implementation Patterns

Workflows

  1. Preloading Critical Resources:

    • Prefix chunk names with preload- (e.g., preload-big-library.js) to preload heavy JS/CSS early.
    • Example:
      // webpack.mix.js
      mix.js('resources/js/big-library.js', 'public/js/preload-big-library.js');
      
  2. Prefetching Future Pages:

    • Use prefetch- prefix for CSS/JS needed on subsequent pages (e.g., prefetch-next-page.css).
    • Ideal for SPAs or multi-page apps with predictable navigation.
  3. Conditional Preloading:

    • Combine with Blade conditionals to load resources only on specific routes:
      @if (Route::is('dashboard'))
          @preload
      @endif
      
  4. Customizing Link Attributes:

    • Override default as/crossorigin via config (config/mix-preload.php):
      'preload' => [
          'as' => 'script',
          'crossorigin' => 'anonymous',
      ],
      

Integration Tips

  • With Laravel Mix: Ensure mix-manifest.json is generated and accessible (default: public/mix-manifest.json). Use mix.version() in your Blade templates to leverage cache-busting.

  • With Inertia.js: Prefetch assets for next potential pages in your SPA:

    @preload  <!-- Prefetches assets for routes defined in your Inertia app -->
    
  • With Alpine.js/React: Dynamically trigger prefetching on route changes:

    // Alpine.js example
    document.addEventListener('alpine:init', () => {
        Alpine.data('prefetcher', () => ({
            prefetch(url) {
                fetch(`/prefetch?url=${url}`)
                    .then(() => console.log('Prefetched:', url));
            }
        }));
    });
    

Gotchas and Tips

Pitfalls

  1. Manifest Path Misconfiguration:

    • Default path: public/mix-manifest.json. If custom, set in config:
      'manifest_path' => 'custom/path/to/manifest.json',
      
    • Debug: Verify the manifest exists and is readable by Laravel.
  2. Incorrect Prefix Naming:

    • Only chunks with preload- or prefetch- prefixes are processed. Typos (e.g., pre-load-) will be ignored.
    • Fix: Double-check mix-manifest.json entries.
  3. Caching Issues:

    • Preload tags may not update if the manifest isn’t rebuilt. Clear cache:
      php artisan cache:clear
      php artisan view:clear
      
    • Tip: Use mix.noVersion() in development to bypass cache.
  4. Resource Hints Overload:

    • Excessive preloads can delay page rendering. Limit to critical resources.
    • Monitor: Use Chrome DevTools (Network tab) to check Preload requests.
  5. Cross-Origin Restrictions:

    • Preloads with crossorigin may fail if the server lacks Access-Control-Allow-Origin headers.
    • Workaround: Set crossorigin="use-credentials" or omit it if not needed.

Debugging

  • Log Manifest Data: Add this to a Blade template to debug:
    @dump(Spatie\MixPreload\Facades\MixPreload::getPreloadLinks())
    
  • Check HTTP Headers: Ensure Link headers aren’t conflicting with preload tags (e.g., from CDNs).

Extension Points

  1. Custom Directives: Extend the package to support @prefetch or @preconnect:

    // app/Providers/AppServiceProvider.php
    use Spatie\MixPreload\Facades\MixPreload;
    
    Blade::directive('preconnect', function ($expression) {
        return "<link rel='preconnect' href='{$expression}'>";
    });
    
  2. Dynamic Prefetching: Hook into Laravel events to prefetch assets dynamically:

    // app/Providers/EventServiceProvider.php
    public function boot()
    {
        event(new \Spatie\MixPreload\Events\PrefetchRequested($url));
    }
    
  3. Conditional Logic: Override the directive logic in a service provider:

    Blade::directive('preload', function () {
        if (auth()->check()) {
            return MixPreload::renderPreloadLinks();
        }
        return '';
    });
    
  4. Asset Prioritization: Use the priority attribute (Chrome-only) for high-priority resources:

    // config/mix-preload.php
    'preload' => [
        'priority' => true, // Adds `priority` attribute
    ],
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport