Preface:
A new IntersectionObserver API can automatically “observe” whether an element is visible if it wants to listen to whether it has entered the viewport, which Chrome 51+ already supports. Because the nature of visible is that a target element intersects with the viewport, the API is called a “intersecting viewer.”
Reference links:www.ruanyifeng.com/blog/2016/1…
Interpretation of the API
// Const Observer = new IntersectionObserver(callback,[options]) const obs = new IntersectionObserver(([{isIntersecting}], observer) => { // entries = [{isIntersecting: true}] }, {}) // Listen on DOM element obs.observe(imgDom) // Cancel DOM listen on obs. serve(imgDom) // Callback will be triggered when the DOM enters the viewable area and leaves the viewable area // - two callback parameters entries , observer // - entries Array of observed element information objects [{element information},{}], // -observer isIntersecting judgment to enter or leave // -observer isIntersecting judgment to enter or leave // -observer isIntersecting judgment to enter or leave // -observer isIntersecting judgment to enter or leave // -observer The default is document // -rootmargin container has no margin // -threshold cross ratio // instance provides two methods // observe(dom) which dom // unobserve(dom) Stop looking at that DOMCopy the code
Concrete implementation code
1. My current project is based on Vue3, so I package lazy loading instructions based on VUe3.0 and IntersectionObserversrc/components/library/index.js
Import defaultImg from '@/assets/images/200.png' // directive const defineDirective = (app) => {// Extend custom directive App. directive('lazyload', {// Vue2 rules: inserted // INSERTED () {} // Vue3 rules: Bindings (el, bindings) {// EL means bindings (EL, bindings) {// EL means bindings (EL, bindings). Const Oberver = new IntersectionObserver(([{isIntersecting}]) => {if (isIntersecting) {// Oberver.src = binding.value // Unsubscribe from oberver.serve (el). El.onerror = () => {// Display default el.src = defaultImg}}}) oberver.observe(el)}})} // Export default { Install (app) {// Install (app) {// Install (app) {// Install (app) {// Install the global component. XtxCarousel) app.component(xtxmore. name, XtxMore) // defineDirective + defineDirective(app)}}Copy the code
Alter img SRC to v-lazyLoad
<img alt="" v-lazyload="cate.picture">
Copy the code