Prefetch
prefetch
是 <link>
元素中 rel
属性的一种取值,用于告诉浏览器可能在未来浏览中需要加载的资源。浏览器可以在空闲时预先获取和缓存这些资源,从而优化用户体验。这意味着在用户浏览网页时,浏览器可以自动获取这些资源,提高网页加载速度。通常由 webpack 等工具实现。
DNS-prefetch
dns-prefetch
是在请求资源之前尝试解析域名的操作。这对于预加载将来可能需要的资源或用户点击的链接目标很有帮助。当引用来自第三方库的资源时,预先解析域名可以加速 CDN 库的加载速度。尽管兼容性略有不足,但与 preconnect
结合使用效果更佳。
Preconnect
preconnect
允许浏览器在正式向服务器发送 HTTP 请求之前执行一系列操作,包括 DNS 解析、TLS 协商和 TCP 握手,从而减少往返延迟,节省用户时间。虽然在 MDN 上未找到相关文档,但其兼容性较好。
CSS懒加载的两种方法
有些 CSS 文件可能会阻碍网页的渲染,因此最好延迟加载。延迟加载的方法包括使用 <link>
标签和 JavaScript 代码。
- 使用
<link>
标签:
html复制<link media="none" onload="this.media='all'" href="<%= BASE_URL %>fonts/LuckiestGuy/index.css" rel="stylesheet">
- 使用 JavaScript 代码:
<code><strong>const</strong> <strong>lazyCss</strong> = (href) => { <strong>const</strong> link = document.<strong>createElement</strong>('link'); link.<strong>setAttribute</strong>('rel', 'stylesheet'); link.<strong>setAttribute</strong>('href', href); link.<strong>setAttribute</strong>('type', 'text/css'); document.<strong>querySelector</strong>('head').<strong>appendChild</strong>(link); }; <em>// 在 App.vue 的 created 或首页的 mounted 中执行</em> <strong>lazyCss</strong>('your-css-file-url.css');</code>
npm包的延迟加载与 @babel/plugin-syntax-dynamic-import
原生 ESM 支持动态加载,返回一个 Promise,但最好配合 Babel 插件使用。
<code><strong>import</strong>('xxx.js') .<strong>then</strong>(module => { console.<strong>log</strong>(module); });</code>
懒加载时手动指定打包文件名
使用 webpack 的代码分割功能,按需加载模块。
<code><strong>const</strong> <strong>CheckinAlert</strong> = () => <strong>import</strong>(<em>/* webpackChunkName: "alert" */</em> '@/themeComponents/theme3/checkinAlert');</code>
减少vendor的大小
可以通过配置 webpack 来减少 vendor 的大小,合理地拆分和打包依赖模块,避免过多的 HTTP 请求。
<code>configureWebpack: config => { config.optimization.splitChunks.cacheGroups.vendors = { <strong>name</strong>(module) { <strong>const</strong> packageName = module.context.<strong>match</strong>(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1].<strong>toLowerCase</strong>(); <strong>return</strong> `package.${packageName.replace('@', '')}`; } }; }</code>
以上是关于优化网页加载速度的一些方法和技巧,希望对大家有所帮助。
暂无评论内容