现代工程项目文件作用域Scope添加lib,以百度地图为例

1.现代工程项目添加lib,最好不要在index.html的head中添加lib.js,下面采用Promise的方式添加

getLib = () => {
    return new Promise(function (resolve, reject) {
        if (window.AMap) resolve(window.AMap); //如果已经加载,则无需

        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.src =
            'https://api.map.baidu.com/library/AreaRestriction/1.2/src/AreaRestriction_min.js';
        // script.onload = resolve
        script.onerror = reject;
        script.onload = function () {
            resolve(window.AMap);
        };
        document.head.appendChild(script);
    });
}

// 使用情况

componentDidMount(){
     getLib().then(() => {
      try {
        const bound = new BMap.Bounds(
          new BMap.Point(o5.lng, o5.lat),
          new BMap.Point(o6.lng, o6.lat)
        );
        BMapLib.AreaRestriction.setBounds(map, bound);
      } catch (e) {
        alert(e);
      }
    });
}

 

对于加载其他lib,可以参考此文档

posted @ 2019-10-16 17:05  Bruce_Grace  阅读(219)  评论(0编辑  收藏  举报