内存不足起因

小程序对用户内存使用进行了限制,如果一个页面的图片过多,会导致内存不足的内部错误

解决办法

对图片进行懒加载,不影响体验的前提下,只渲染当屏的图片,屏外图片,显示缺省图

实践分析

  • 图片最多的情况就是列表(头图或图片列表),为了性能,一般会滚动加载,而在小程序中,需要借助scroll-view/swiper组件,为了不影响用户体验,就不能让之前以渲染的列表元素失去占位

  • 要判断元素是否在当屏,就要知道一些高度信息(屏幕高,滚动高度,元素高度),但是元素高度在小程序中不能动态获取,所以就需要列表时定高的

  • 代码

    wxml文件

       !--        showIndex为当屏中首列表元素的索引值        scrollLoad滚动加载        scrollHide图片当屏渲染    --        scroll-view wx:if="{{isNet}}" scroll-y="true"        bindscrolltolower="scrollLoad" bindscroll="scrollHide"            view wx:if="{{total}}"            block wx:for="{{imgDatas}}"                view                    image wx:if="{{showIndex + 24 index && showIndex - 6 index}}" src="{{item.pic.url}}" mode="aspectFill"/image                /view            /block        /view        /scroll-view

    计算showIndex的方法,可作为公用方法

       /**     * offetHeight  滚动计算部分到顶部距离     * scrollTop   滚动高度     * height      每个模块的高度     * colunm      列数    **/        function countIndex (offetHight, scrollTop, height, colunm) {        // 单例获取屏幕宽度比        if (!countIndex.pix) {            try {              let res = wx.getSystemInfoSync()              countIndex.pix = res.windowWidth / 375            } catch (e) {              countIndex.pix = 1            }        }        let scroll = scrollTop - offetHight * countIndex.pix        let hei = height * countIndex.pix        return scroll 0 ? Math.floor(scroll / hei) * colunm : 0    }

    js文件

       let wxTools = require('../../untils/wxTools.js')        Page({        data: {            scrollData: {                offetHeight: 15, // px                height: 80, // px                colunm: 3            },            showIndex: 0        },        scrollHide (e) {            let data = [                this.data.scrollData.offetHeight,                e.detail.scrollTop,                this.data.scrollData.height,                this.data.scrollData.colunm            ]                        let index = wxTools.countIndex(...data)                this.setData({                showIndex: index            })        }    })

    具体要渲染多少的元素,自己来定,这里没有放到countIndex中加入计算,例如wxml中的{{showIndex + 24 index && showIndex - 6 index}},会渲染30个元素的图片

    TAG标签: 微信小程序内存优化

    http://www.xiaochengxub.com/read-101477.html