網站首頁 編程語言 正文
正常加載
為了看的方便,index.js中的代碼非常簡單
console.log('index.js執行了') import { test } from './test.js' document.getElementById('btn-wrap').onclick = function () { test() }
test.js
console.log('test.js執行了') export function test() { const value = 'hello world' console.log('test value: ', value) }
在index.html中添加按鈕
<button id='btn-wrap'>點擊</button>
執行webpack命令:
可以看到沒有點擊按鈕時,test.js就已經加載了 。如果test.js比較大,加載比較耗性能。我們就希望能在需要使用的時候在加載
懶加載
修改index.js中的代碼
console.log('index.js執行了') // import { test } from './test.js' // document.getElementById('btn-wrap').onclick = function () { // test() // } document.getElementById('btn-wrap').onclick = function () { console.log('==== 點擊按鈕') import(/*webpackChunkName:'test' */"./test") .then(({test}) => { console.log('test加載成功') test() }) .catch(error => { console.log('test加載失敗 error:', error) }) }
再次執行webpack命令,在瀏覽器中查看日志
點擊按鈕之前只加載了index.js
點擊按鈕:
可以看到點擊按鈕之后test.js才執行。
預加載
懶加載實現了js文件按需加載,在需要使用時才進行加載,但是如果js文件非常大加載速度比較慢,在使用時再加載就會使頁面出現卡頓。為了優化這個問題,可以使用Prefetch先預加載。
沒有使用預加載
點擊按鈕之前不會加載test.js文件
點擊按鈕之后才會去加載test.js文件
使用預加載
設置webpackPrefetch:true
使用預加載
document.getElementById('btn-wrap').onclick = function () { console.log('==== 點擊按鈕') import(/*webpackChunkName:'test' ,webpackPrefetch:true*/"./test") .then(({test}) => { console.log('test加載成功') test() }) .catch(error => { console.log('test加載失敗 error:', error) }) }
點擊按鈕之前就預加載了test.js文件:
點擊按鈕:
總結
正常加載:很多資源并行加載,同一時間加載多個文件
懶加載:需要時才加載
預加載:等其他資源加載完畢,瀏覽器空閑了,再偷偷加載被設置為預加載的資源
原文鏈接:https://blog.csdn.net/Celester_best/article/details/122120349
相關推薦
- 2022-07-17 使用SQL語句實現查詢排序,順序和倒序_MsSql
- 2022-08-12 Go單元測試對GORM進行Mock測試_Golang
- 2022-07-21 cartographer 編譯遇到 abseil的問題
- 2022-07-07 Python自動化測試selenium指定截圖文件名方法_python
- 2022-11-25 Python?Django教程之模型中字段驗證詳解_python
- 2022-11-24 詳解如何實現一個Kotlin函數類型_Android
- 2022-11-15 python管理包路徑之pycharm自動解決包路徑注冊_python
- 2022-04-11 C#實現簡易計算器功能(1)(窗體應用)_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支