vue優化之骨架屏

1. 什麼是骨架屏

如果一個web頁面加載內容過多,刷新的時候會有空白頁,造成不好的用戶體驗,但是如果加入骨架屏可以改善這一問題,骨架屏可理解爲頁面加載前的簡單呈現版本,當頁面加載完成,骨架屏各個佔位區域被實際資源替換,可讓用戶覺得內容正在加載即將呈現,體驗更加流暢。實際應用比較廣泛,CSDN,小米商城等很多大型網站都用到了骨架屏方案。

2.如何實現

  • 不建議: vue框架的原理是替換掉index.html中id爲app的div部分,如果加載內容多,這一部分渲染就會慢(如果也不採用按需加載),可以在body部分加入骨架屏需要的圖片,但是並不優雅,修改不方便,如果骨架屏內容過多,在這裏展示顯然不合適,而且無法實現多頁面骨架屏,因此不推薦這種
 <body>
     <img src="../static/img/skeleton_bg.jpg" style="width: 100%;height: 100%;position: absolute;left:0;top:0;right:0;bottom:0;margin: auto"/>
     <div id="app"></div>
  </body>
  • 建議:如何合理且優雅地實現骨架屏
  • 代碼實現:
  1. 在src目錄下新建骨架屏頁面Skeleton.vue、入口entry-skeleton.js

    entry-skeleton.js
    import Vue from 'vue'
    import Skeleton from './Skeleton'
    export default new Vue({
      components: {
        Skeleton
      },
      template: '<Skeleton />'
    })
    
    Skeleton.vue
    <!--骨架屏-->
    <template>
      <div class="skeleton">
        <img src="../static/img/skeleton_bg.jpg" />
      </div>
    </template>
    
    <script>
      export default {
        name: 'skeleton',
        methods: {
        }
      }
    </script>
    
    <style scoped>
    img{
      width: 100%;
      height: 100%;
      position: absolute;
      left:0;top:0;
      right:0;
      bottom:0;
      margin: auto
    }
    </style>
    
  2. 創建了骨架頁面,不放到index裏面也是不行的,因此在打包的時候做下面的處理,在build文件夾裏新建文件webpack.skeleton.conf.js,目的是讀取entry-skeleton,寫入打包配置
    'use strict';
    const path = require('path')
    const merge = require('webpack-merge')
    const baseWebpackConfig = require('./webpack.base.conf')
    const nodeExternals = require('webpack-node-externals')
    
    const config = require('../config')
    const utils = require('./utils')
    const isProduction = process.env.NODE_ENV === 'production'
    const sourceMapEnabled = isProduction
      ? config.build.productionSourceMap
      : config.dev.cssSourceMap
    
    function resolve(dir) {
      return path.join(__dirname, dir)
    }
    
    let skeletonWebpackConfig = merge(baseWebpackConfig, {
      target: 'node',
      devtool: false,
      entry: {
        app: resolve('../src/entry-skeleton.js')
      },
      output: Object.assign({}, baseWebpackConfig.output, {
        libraryTarget: 'commonjs2'
      }),
      externals: nodeExternals({
        whitelist: /\.css$/
      }),
      plugins: []
    })
    
    //important: enable extract-text-webpack-plugin,讓顏色生效
    // 重點配置
    skeletonWebpackConfig.module.rules[0].options.loaders = utils.cssLoaders({
      sourceMap: sourceMapEnabled,
      extract: true
    })
    
    module.exports = skeletonWebpackConfig
    
  3. 打包,在webpack.prod.conf.js和webpack.dev.conf.js 的plugins部分,加入plugin
    new SkeletonWebpackPlugin({
         webpackConfig: require('./webpack.skeleton.conf'),
         quiet: true,
       }),
    
    運行一下,在加載頁面時,有如下效果
    在這裏插入圖片描述

點擊加入羣聊【小程序/HTML/WPF交流】,一起學習交流:663077768

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章