日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

webpack的懶加載和預加載詳解(webpack按需加載)

作者:Celester_best ? 更新時間: 2022-03-18 編程語言

正常加載

為了看的方便,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

欄目分類
最近更新