gpt4 book ai didi

javascript - 带有外部脚本加载的 jQuery 竞争条件

转载 作者:行者123 更新时间:2023-11-28 04:03:53 24 4
gpt4 key购买 nike

仅当幻灯片数量超过一定数量时,我才尝试有条件地加载光滑 slider jQuery 库。否则,我不想使用 slider 。

如果我不将脚本附加到 head 标记,而是在页面上发生此脚本的位置内联运行它,则效果很好。然而,一旦它按如下所示执行,它就会提示 slick() 不是一个函数。

如何确保 slick 首先完成加载,而不使用 require.js?

<script>
$(document).ready(function () {

var slideCount = $('div.recipe.slide').length;

if(slideCount > 4) {
$('head').append('<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.css">');
$('head').append('<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.css">');
$('body').append('<script src="//cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.js"><\/script>');
}

$('.image-slider').slick({
arrows: true,
autoplay: true,
autoplaySpeed: 2000,
dots: false,
mobileFirst: true,
slidesToShow: 4,
responsive: [
{
breakpoint: 1,
settings: {
arrows: false,
},

breakpoint: 479,
settings: {
centerMode: true,
}
}
]
});
});
</script>

最佳答案

如果像这样加载,则使用脚本:

 /*----------------------------------------------------------------------*/
function load_js_file(_url, _callback){
_callback=_callback||function(){};
_url=_url||'';
var script = document.createElement('script');
script.src = _url;
script.type = 'text/javascript';
script.onload = function() {
_callback();
};
document.getElementsByTagName("head")[0].appendChild(script);
}

/*----------------------------------------------------------------------*/


function load_css_file(_url, _callback){
_callback=_callback||function(){};
_url=_url||'';
var script = document.createElement('link');
script.href = _url;
script.type = 'text/css';
script.rel = 'stylesheet';
script.onload = function() {
_callback();
};
document.getElementsByTagName("head")[0].appendChild(script);
}

/*----------------------------------------------------------------------*/




$(document).ready(function () {

var slideCount = $('div.recipe.slide').length;
if(slideCount > 4) {

load_css_file('//cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.css', function(){
load_css_file('//cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.css', function(){
load_js_file('//cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.js', function(){


$('.image-slider').slick({
arrows: true,
autoplay: true,
autoplaySpeed: 2000,
dots: false,
mobileFirst: true,
slidesToShow: 4,
responsive: [
{
breakpoint: 1,
settings: {
arrows: false
},

breakpoint: 479,
settings: {
centerMode: true
}
}
]
});

});
});
});


}

});

关于javascript - 带有外部脚本加载的 jQuery 竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46866716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com