简体   繁体   中英

Lazy load image in tippy.js Tooltip?

I'm using tippy.js to generate tooltips. Everything works fine however I have allot of tool tips each with different image content loaded. To reduce load time I would like to lazy load the image to only apear when the tooltip is visible.

I know tippy.js has a built in function to call AJAX content ( https://atomiks.github.io/tippyjs/ajax/ ) - however the content I want to load is in the HTML and I do not want to have to write separate javascript for each tooltip. Ideally it would be great to somehow fetch the img scr of the particular tip I am hovering and than call it to load with the onShow(instance) ~ ie fetch('$(this).find("img").data("src");'). I tried a few variations of this but nothing is working.

Here is a codepen (without) lazy loading images: https://codepen.io/jinch/pen/aboNOvP?editors=1010

I have tried to manipulate the AJAX example on their website to work but had not luck (see below).

tippy('body .tippy', {
            theme: 'google',
            touchHold: true,
            hideOnClick: false,
            interactive: true,
            placement: 'left',
            distance: 20,
            arrow: true,
            animateFill: false,
            animation: 'shift-away',

              onShow(instance) {
                if (instance.state.ajax === undefined) {
                  instance.state.ajax = {
                    isFetching: false,
                    canFetch: true,
                  }
                }
                if (instance.state.ajax.isFetching || !instance.state.ajax.canFetch) {
                  return
                }

                fetch('$(this).find("img").data("src")')
                  .then(response => response.blob())
                  .then(blob => {
                  })
                  .catch(error => {
                    // ...
                  })
                  .finally(() => {
                    instance.state.ajax.isFetching = false
                  })
              },
              onHidden(instance) {
                instance.setContent('Loading...')
                instance.state.ajax.canFetch = true
              },
          })

The idea result would having the images load only when called to reduce the initial load time of the page.

感谢@atomiks,您可以在这里找到答案: https : //github.com/atomiks/tippyjs/issues/562#issuecomment-521650755

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM