欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

webpack的懶加載和預(yù)加載詳解

 更新時(shí)間:2021年12月28日 09:08:16   作者:Celester_best  
這篇文章主要為大家介紹了webpack的懶加載和預(yù)加載,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

正常加載

為了看的方便,index.js中的代碼非常簡(jiǎn)單

console.log('index.js執(zhí)行了')
import { test } from './test.js'
document.getElementById('btn-wrap').onclick = function () {
    test()
}

test.js

console.log('test.js執(zhí)行了')
export function test() {
    const value = 'hello world'
    console.log('test value: ', value)
}

在index.html中添加按鈕

    <button id='btn-wrap'>點(diǎn)擊</button>

執(zhí)行webpack命令:

可以看到?jīng)]有點(diǎn)擊按鈕時(shí),test.js就已經(jīng)加載了 。如果test.js比較大,加載比較耗性能。我們就希望能在需要使用的時(shí)候在加載

懶加載

修改index.js中的代碼

console.log('index.js執(zhí)行了')
// import { test } from './test.js'
// document.getElementById('btn-wrap').onclick = function () {
//     test()
// }
document.getElementById('btn-wrap').onclick = function () {
    console.log('====  點(diǎn)擊按鈕')
    import(/*webpackChunkName:'test' */"./test")
        .then(({test}) => {
            console.log('test加載成功')
            test()
        })
        .catch(error => {
            console.log('test加載失敗 error:', error)
        })
}

再次執(zhí)行webpack命令,在瀏覽器中查看日志

點(diǎn)擊按鈕之前只加載了index.js

點(diǎn)擊按鈕:

可以看到點(diǎn)擊按鈕之后test.js才執(zhí)行。

預(yù)加載

懶加載實(shí)現(xiàn)了js文件按需加載,在需要使用時(shí)才進(jìn)行加載,但是如果js文件非常大加載速度比較慢,在使用時(shí)再加載就會(huì)使頁面出現(xiàn)卡頓。為了優(yōu)化這個(gè)問題,可以使用Prefetch先預(yù)加載。

沒有使用預(yù)加載

點(diǎn)擊按鈕之前不會(huì)加載test.js文件

點(diǎn)擊按鈕之后才會(huì)去加載test.js文件

使用預(yù)加載

設(shè)置webpackPrefetch:true使用預(yù)加載

document.getElementById('btn-wrap').onclick = function () {
    console.log('====  點(diǎn)擊按鈕')
    import(/*webpackChunkName:'test' ,webpackPrefetch:true*/"./test")
        .then(({test}) => {
            console.log('test加載成功')
            test()
        })
        .catch(error => {
            console.log('test加載失敗 error:', error)
        })
}

點(diǎn)擊按鈕之前就預(yù)加載了test.js文件:

點(diǎn)擊按鈕:

總結(jié)

正常加載:很多資源并行加載,同一時(shí)間加載多個(gè)文件

懶加載:需要時(shí)才加載

預(yù)加載:等其他資源加載完畢,瀏覽器空閑了,再偷偷加載被設(shè)置為預(yù)加載的資源

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!

相關(guān)文章

最新評(píng)論