所以基本上我想为我的网站制作一些延迟加载代码。
每个 Youtube 视频都有一个缩略图,通常 URL 是这样的:
http://img.youtube.com/vi/<THEVIDEOID>/maxresdefault.jpg
我想检测一下这个,如果是真的,这可能是一个点击事件,点击图像后,你会得到 iframe 并且可以播放视频。
现在,我知道互联网上有成千上万的外部插件,但我不想加载任何其他代码,只是这个脚本工作真正需要的功能(我像任何人一样讨厌大加载时间其他)。
有时外部插件对我来说有成千上万个不必要的功能,比如检查我选择的点击方法或滚动方法的每个负载,以及其他无用的东西。
这就是为什么我决定尝试构建自己的。
我看到了this post在搜索结果中,但我想以 jQuery 方式构建它。
注意:
这需要一个 WordPress 网站,这就是我使用 jQuery
而不是 $
的原因。
这就是我现在拥有的:
jQuery(document).ready(function() {
function youtubecheck(){
var myregexp = /[a-z,A-Z,0-9]/g;//Regexp for videoid
var imageurl="http://img.youtube.com/vi/"+myregexp+"/maxresdefault.jpg"; // This doesn't sounds right, I need to find out something else.
if (jQuery("img").attr("src")=== "imageurl"){
var autoplay="?autoplay=1/"//this for iframe
jQuery(this).addClass("YT-image"); // Obviously we need class, because we don't whant to do this with all images, just with YT-imgaes.
jQuery(".YT-image").click(function() {
jQuery(".YT-image").replaceWith('<iframe width="560" height="315" src="https://www.youtube.com/embed/'+myregexp+autoplay+'" frameborder="0" allowfullscreen></iframe>'); // maybe we need each for every image? Also I'm not sure about "myregexp" variable in here.
});
}
}
youtubecheck();
});
最佳答案
更改了 if 条件和正则表达式
jQuery(document).ready(function() {
function youtubecheck() {
if (/img\.youtube\.com\/vi\/[a-z,A-Z,0-9]+\/maxresdefault\.jpg/g.test(jQuery("img").attr("src"))) {
var videoId = /img\.youtube\.com\/vi\/(.*?)\/maxresdefault\.jpg/g.exec(jQuery("img").attr("src"))[1];
var autoplay = "?autoplay=1/"; //this for iframe
jQuery("img").addClass("YT-image"); //Obviously we need class, becouse we don't whant to do this with all images, just with YT-imgaes.
jQuery(".YT-image").click(function() {
jQuery(this).replaceWith('<iframe width="560" height="315" src="https://www.youtube.com/embed/' + videoId + autoplay + '" frameborder="0" allowfullscreen></iframe>'); // maybe we need each for every image? Also I'm not sure about "myregexp" varible in here.
});
}
}
youtubecheck();
});
更新了有效的代码
关于javascript - 如何检查 img src 是否以 http ://img. youtube.com/vi/开头并在任何字符之后并替换为 youtube 视频 iframe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36619941/