I want to lazy load the youtube video with iframe API. ie. load only the poster image in the beginning and when user clicks on it then only load the actual image and its content.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
How about this?
HTML
JS
DEMO
Most of this is taken from the getting started section on the youtube page.
This example loads the video when it is ready.
So we change it up a bit to add in a placeholder image and on click hide the image and play the video.
Wrap the tag (step 2) in function
Add an image Check this question for more details on sizes.
Then on click hide the placeholder image and load the player
Final result can be seen below.
<iframe loading="lazy"
This feature allows lazy loading YouTube
iframe
embeds only when the user scrolls over them.Here is a working jsfiddle: https://jsfiddle.net/cirosantilli/3p0tk5nc/1/ that I have tested on Chromium 81. You can see on the developer tools "network" tab that the frames only load when you scroll over them.
It does not work on Stack Overflow snippets for some reason however because YouTube videos appear to not work on Stack Overflow in general, not because of
loading="lazy"
in particular.More details at: lazy load iframe (delay src http call) with jquery
Finally it worked, below code is in angularJS.
HTML
JS
Why load the videos on click, and not just when the user sees them? Use jQuery.Lazy and you have nothing more to do. :)
Add the Plugin to your Page: (you will need jQuery or Zepto as well)
Prepare your iFrames: (note the
data-loader
anddata-src
attributes)And start using Lazy:
That's it! The iFrames will be loaded whenever the user reaches them by scrolling. More inormations here.