[Webpack 2] Maintain sane file sizes with webpack code splitting

本文介绍了如何通过代码分割实现懒加载来提升大型单页应用的性能。通过按需加载特定功能所需的代码,可以显著减少初始加载时间并提高用户体验。

As a Single Page Application grows in size, the size of the payload can become a real problem for performance. In this lesson, learn how to leverage code splitting to easily implement lazy loading for your application to load only the code necessary for a particular feature or functionality.

 

Here we loads facts at the beginning. So this will be bundled into the bundle.js file. This is not good enought if the application becomes large.

import {$on} from './helpers'
import * as facts from './facts'

const factsList = document.getElementById('facts-list')
const factText = document.getElementById('fact-text')

$on(factsList, 'click', ({target: {dataset: {fact}}}) => {
  if (!facts) {
      factText.innerText = facts.defaultFact
      return
  }
   factText.innerText = facts[fact]
})

 

So what we want to do is loading the file on demand. And wepack will help to load file on runtime.

import {$on} from './helpers'

const factsList = document.getElementById('facts-list')
const factText = document.getElementById('fact-text')

$on(factsList, 'click', ({target: {dataset: {fact}}}) => {
    if (!fact) {
        return System.import('./facts/default-fact').then(setFactText)
    }
    System.import('./facts/' + fact).then(setFactText)

    function setFactText({fact: animalFact}) {
        factText.innerText = animalFact
    }
})

To do that, we need to tell Webpack to import file when it needed by using :

System.import('./facts/' + fact)

It returns a promise, then we do parse the stuff:

    System.import('./facts/' + fact).then(setFactText)

    function setFactText({fact: animalFact}) {
        factText.innerText = animalFact
    }

 

转载于:https://www.cnblogs.com/Answer1215/p/5608611.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值