为了仅在触摸设备中加载 jquery 滑动脚本,我使用现代化器检测它并附加脚本(如果是触摸),如下所示:
/**/
if ( modernizer.touch ) {
var js = jQuery("<script>");
css.attr({
type: "text/css",
src: base_url + "/js/jquery-touch-swipe.js?p1"
});
$("head").append(css);
$this.swipe( function( e, dx, dy ){
if( dx < 0 ){
$this.find('.next').click();
} else {
$this.find('.prev').click();
}
});
}
问题是,之后,swipe
功能还没有准备好。我可以使用 setTimeout
但我也不能确定,
如何确保附加脚本已准备就绪?
我尝试过这样的:
if ( modernizer.touch ) {
var js = jQuery("<script>");
css.attr({
type: "text/css",
src: base_url + "/js/jquery-touch-swipe.js?p1",
id: 'swipe'
});
$("head").append(css);
$('#swipe').load(function() {
$this.swipe( function( e, dx, dy ){
if( dx < 0 ){
$this.find('.next').click();
} else {
$this.find('.prev').click();
}
});
});
}
但没有成功
最佳答案
您可以使用$.getScript
并使用其成功回调函数,该函数将在脚本加载后执行但不一定执行。
if (Modernizr.touch) {
$.getScript(base_url + "/js/jquery-touch-swipe.js?p1", function () {
//Operation which you want to perform
});
}
关于javascript - 动态添加.js文件,如何知道它何时准备好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24573096/