需求:在使用cordova+jquerymobile开发H5 APP的时候,希望在使用高德地图的页面的pageshow方法中,加载地图js,即地图的懒加载功能。
实现方法:
之前错误的方式:
$.getScript("http://webapi.amap.com/maps?v=1.4.0&key=xxx&plugin=AMap.LineSearch");
//使用AMap
会报AMap is notundefined的错误。
原因是什么呢?参考这篇文章
jquery .getscript() callback when script is fully loaded and executed其实就是这个方法是去加载js,但是其不保证立刻fullyloaded。
所以应该这样使用
if (typeof(AMap) == "undefined") {
$.getScript("http://webapi.amap.com/maps?v=1.4.0&key=xxx&plugin=AMap.LineSearch").done(function (script, textstatus) {
if (textstatus == "success" && typeof (AMap) != undefined) {
//所有使用AMap的内容
execBikePointMap();
} else {
showAlert("无法加载地图,请打开网络");
}
});
}else {
execBikePointMap();
}
所以在一个js中如果要保证另一个js完整加载,那么可以参考上述的实现方式。