我正在合并使用YouTube iFrame API和通过defer设置了标志的脚本标记加载的jQuery .必须设置延迟标记,因为客户端具有完美的Google页面洞察分数,并希望保持该分数.
YouTube API在完全加载并可以使用后,immediatley调用我定义的功能onYouTubeIframeAPIReady.然后它会调用onPlayerReady播放器完全加载和渲染.
我希望在这个函数中使用jQuery,但只是在onPlayerReady函数中使用jQuery将创建一个竞争条件(希望jQuery库在onPlayerReady被调用时已完成加载).
它发生在我身上一个可行的解决方案是使用onPlayerReady函数在调用一个测试播放器和jQuery的函数之前设置一个变量.另一个函数在jQuery准备就绪时设置一个变量,并调用相同的测试函数.
我有一些代码可以工作,但检查jQuery的部分对我来说似乎很乱,并且还引入了少量额外的不必要的延迟.我想知道是否有人知道更好的方式来运行即时jQuery变得可用的东西.基本上,jQuery的回调是否可以内置到库中?
我目前的代码如下:
var ready = {
'jquery': false,
'youtube' false
},
testJQueryLoaded;
testJQueryLoaded = function() {
if(typeof jQuery == 'undefined') {
window.setTimeout(function() {
testJQueryLoaded();
}, 25);
return;
}
ready.jquery = true;
postLibraryLoad();
};
testJQueryLoaded();
function onYouTubeIframeAPIReady() {
// Stuff
};
function onPlayerReady() {
ready.youtube = true;
postLibraryLoad();
};
function postLibraryLoad() {
if(!ready.jquery || !ready.youtube) {
return;
}
// More stuff
};
Run Code Online (Sandbox Code Playgroud)
正如@KevinB所建议的,您可以利用load特定<script>元素的事件
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" defer></script>
<script>
const dojQueryStuff = (el, params) => this.jQuery(el, params).appendTo("body");
</script>
<script>
document
.querySelector("script[src$='3.2.1/jquery.min.js']")
.onload = event => {
console.log(event.target.src);
dojQueryStuff("<div>", {
html: "jQuery version: " + this.jQuery().jquery + " loaded"
});
}
</script>
</head>
<body>
</body>
</html>Run Code Online (Sandbox Code Playgroud)