如何解决主线程阻塞导致渲染不及时

做项目遇到这么一个场景,一个长列表,需要手写滚动条,列表中图片属于懒加载,滑动以后,加载图片的过程会阻塞线程,导致滑动条的移动会有延迟。那么有没有办法让渲染线程和主线程同步执行呢?目前滑动条是通过监听容器的滚动然后使用绝对定位改变y值实现的。

template:

<view class="scrollBar" :style="{height:`${appHeight}px`}">
    <view class="bar" :style="{top:`${scrollBarY}px`></view>
</view>

script 监听滚动事件片段:

// listHeight为列表的总高度,appHeight为显示区域的高度
handleScroll(e){
    let y = Math.abs(e.contentOffset.y);
    this.scrollBarY = y / this.listHeight * this.appHeight;
}

 

效果:

 

 

问题已解决。小程序里的视图层和逻辑层本身就是独立运行的,我原来的写法是在逻辑层实现,那么把这个操作放进视图层里运行即可解决问题。使用BindingX实现,文档:https://alibaba.github.io/bindingx/guide/cn_introduce

简单案例:

// uniapp nvue
<template>
  <view class="wrapper">
    <list class="list" ref="list" :style="{height:`${appHeight}px`}" :show-scrollbar="false">
      <cell class="item" v-for="i in len" :key="i">
        <text>{{ i }}</text>
      </cell>
    </list>
    <view class="scrollBar" :style="{height:`${appHeight}px`}">
      <view class="bar" ref="scrollBar"></view>
    </view>
  </view>
</template>

<script>
const Binding = uni.requireNativePlugin('bindingx')
export default {
  data() {
    return {
      len:100
    }
  },
  mounted() {
    this.$nextTick(()=>{
      let appHeight = this.appHeight,
        listHeight = (95 + 5) * this.len;
      Binding.bind({
        anchor: this.getEl(this.$refs.list),
        eventType:'scroll',
        props:[
          {
            element: this.getEl(this.$refs.scrollBar),
            property: 'transform.translateY',
            expression: `y / ${listHeight} * ${appHeight}`
          }
        ]
      })
    })
  },
  methods: {
    getEl(el) {
      if (typeof el === 'string' || typeof el === 'number') return el;
      if (WXEnvironment) {
        return el.ref;
      } else {
        return el instanceof HTMLElement ? el : el.$el;
      }
    },
  },
  computed:{
    appHeight(){
      return this.$store.state.appHeight;
    }
  }
}
</script>

<style>
.item{
  color: white;
  border-top-width: 5px;
  height: 95px;
  background-color: #007AFF;
  align-items: center;
  justify-content: center;
}
.scrollBar {
  position: fixed;
  right: 0;
  top: 0;
  z-index: 10;
  width: 20px;
}
.bar {
  position: absolute;
  background-color: #232323;
  width: 15px;
  right: 3px;
  border-radius: 20px;
  height: 60px;
}
</style>

 

既然都懒加载了,懒加载当前页之外,缓存下一页和上一页需要的图像也不是个事。这样翻页的时候就只需要把缓存里的数据翻出来,然后开个子线程去更新缓存。如果内存够用,可以缓存当前页附近几页,和表头表尾附近几页。

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps: 问答会员年卡【8折】购 ,限时加赠IT实体书,即可 享受50次 有问必答服务,了解详情>>>https://t.csdnimg.cn/RW5m