阿里云主机折上折
  • 微信号
Current Site:Index > The generation control of preloading instructions

The generation control of preloading instructions

Author:Chuan Chen 阅读数:12068人阅读 分类: 构建工具

Performance Optimization: Control of Preload Directive Generation

Vite.js automatically generates preload directives during the build process, which can significantly improve page load performance. By rationally controlling the generation of these directives, developers can further optimize application performance, especially when dealing with large projects or complex dependency relationships.

How Preload Directives Work

Vite.js uses the <link rel="modulepreload"> directive to preload critical modules. When the browser parses the HTML, these directives request and cache modules in advance, reducing subsequent loading delays. For example:

<link rel="modulepreload" href="/src/main.js" />
<link rel="modulepreload" href="/src/components/Header.vue" />

This mechanism is particularly useful for applications with complex dependency relationships, as it significantly reduces performance issues caused by waterfall loading.

Configuring Preload Directive Generation

Vite.js provides options such as build.rollupOptions.output.manualChunks and build.rollupOptions.output.inlineDynamicImports to control code splitting and preload behavior. In vite.config.js:

export default {
  build: {
    rollupOptions: {
      output: {
        manualChunks: (id) => {
          if (id.includes('node_modules/lodash')) {
            return 'lodash'
          }
          if (id.includes('node_modules/axios')) {
            return 'axios'
          }
        }
      }
    }
  }
}

Custom Preload Strategies

For scenarios requiring finer control, you can use build.rollupOptions.output.entryFileNames and build.rollupOptions.output.chunkFileNames to adjust output filenames, thereby influencing preload behavior:

export default {
  build: {
    rollupOptions: {
      output: {
        entryFileNames: 'assets/[name]-[hash].js',
        chunkFileNames: 'assets/chunks/[name]-[hash].js',
        assetFileNames: 'assets/[name]-[hash][extname]'
      }
    }
  }
}

Disabling Preload for Specific Modules

In some cases, preloading may not be suitable for all modules. You can disable preload for specific modules using the build.rollupOptions.output.experimentalPreload configuration:

export default {
  build: {
    rollupOptions: {
      output: {
        experimentalPreload: {
          exclude: (chunkInfo) => {
            return chunkInfo.name.includes('lazy-loaded')
          }
        }
      }
    }
  }
}

Synergy Between Dynamic Imports and Preloading

Dynamic imports (import()) can work in tandem with preload directives. Vite.js automatically generates preload directives for dynamically imported modules, but you can control this behavior with comments:

// Disable preload for specific dynamic imports
const module = await import(
  /* webpackIgnore: true */
  './lazy-module.js'
)

Preloading Critical CSS Resources

In addition to JavaScript modules, preloading CSS resources is equally important. Vite.js automatically generates preload directives for critical CSS:

<link rel="preload" href="/assets/style.css" as="style" />

You can adjust this behavior through configuration:

export default {
  build: {
    cssCodeSplit: true,
    rollupOptions: {
      output: {
        assetFileNames: (assetInfo) => {
          if (assetInfo.name.endsWith('.css')) {
            return 'assets/css/[name]-[hash][extname]'
          }
          return 'assets/[name]-[hash][extname]'
        }
      }
    }
  }
}

Evaluating the Performance Impact of Preload Directives

While preload directives can improve performance, excessive use may cause network congestion. You can use Chrome DevTools' Performance panel to evaluate preload effectiveness:

  1. Record the page loading process.
  2. Analyze critical request paths.
  3. Check if preload directives are working as expected.
  4. Adjust configurations to optimize critical paths.

Advanced Configuration: Custom Preload Functions

For scenarios requiring complete control over preload logic, you can implement custom preload functions:

export default {
  build: {
    rollupOptions: {
      output: {
        experimentalPreload: {
          map: (chunkInfo) => {
            if (chunkInfo.isEntry) {
              return { files: [chunkInfo.fileName], type: 'module' }
            }
            return null
          }
        }
      }
    }
  }
}

Synergistic Optimization of Preloading and HTTP/2

In an HTTP/2 environment, preload strategies can be more aggressive due to HTTP/2's multiplexing feature, which reduces connection overhead:

export default {
  server: {
    http2: true,
    headers: {
      'Link': [
        '</assets/main.js>; rel=preload; as=script',
        '</assets/main.css>; rel=preload; as=style'
      ]
    }
  }
}

Cache Strategies for Preload Directives

A reasonable cache strategy maximizes the effectiveness of preloading. Configure the Cache-Control header to ensure preloaded resources are cached correctly:

export default {
  server: {
    headers: {
      'Cache-Control': 'public, max-age=31536000, immutable'
    }
  }
}

Priority Control for Preload Directives

The as attribute can specify resource types, helping the browser determine loading priority:

<link rel="preload" href="/assets/font.woff2" as="font" type="font/woff2" crossorigin>

In the Vite configuration, you can use plugins to automatically add these attributes:

import { createHtmlPlugin } from 'vite-plugin-html'

export default {
  plugins: [
    createHtmlPlugin({
      minify: true,
      inject: {
        data: {
          preloadLinks: generatePreloadLinks() // Custom generation function
        }
      }
    })
  ]
}

Cross-Origin Considerations for Preload Directives

For cross-origin resources, the crossorigin attribute must be set correctly:

<link rel="preload" href="https://cdn.example.com/lib.js" as="script" crossorigin>

Ensure CDN resources are handled properly in the Vite configuration:

export default {
  build: {
    assetsInlineLimit: 0,
    rollupOptions: {
      external: ['https://cdn.example.com/lib.js']
    }
  }
}

Debugging Tips for Preload Directives

When debugging preload behavior, you can use the following methods:

  1. Filter preload requests in Chrome DevTools' Network panel.
  2. Use the performance.getEntriesByType('resource') API to obtain preload resource information.
  3. Check console warnings to identify preload issues.
// Check preloaded resources in the console
performance.getEntriesByType('resource')
  .filter(entry => entry.initiatorType === 'link' && entry.name.includes('.js'))
  .forEach(entry => console.log(entry))

Integration of Preload Directives with Service Workers

Service Workers can further enhance preloading by enabling more granular resource caching strategies:

// sw.js
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('preload-cache').then((cache) => {
      return cache.addAll([
        '/assets/main.js',
        '/assets/main.css'
      ])
    })
  )
})

Register the Service Worker in the Vite configuration:

import { VitePWA } from 'vite-plugin-pwa'

export default {
  plugins: [
    VitePWA({
      registerType: 'autoUpdate',
      workbox: {
        globPatterns: ['**/*.{js,css,html}']
      }
    })
  ]
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.