动态加载js
异步加载百度地图
export default { init: function (){ const AK = "your key"; const BMap_URL = "https://api.map.baidu.com/api?v=3.0&ak="+ AK +"&s=1&callback=onBMapCallback"; return new Promise((resolve, reject) => { // 如果已加载直接返回 if(typeof BMap !== "undefined") { resolve(BMap); return true; } // 百度地图异步加载回调处理 window.onBMapCallback = function () { // console.log("百度地图脚本初始化成功..."); resolve(BMap); }; // 插入script脚本 let scriptNode = document.createElement("script"); scriptNode.setAttribute("type", "text/javascript"); scriptNode.setAttribute("src", BMap_URL); document.body.appendChild(scriptNode); }); } }
MP.init().then((BMap)=>{ this.init() });
动态加载js通用方法
function setScript(src){ return new Promise((resolve,reject)=>{ let scriptNode=document.createElement('script'); scriptNode.src=src; document.head.appendChild(scriptNode); scriptNode.onload=function(){ resolve(); } }) } //调用 setScript('1.js').then(()=>{ alert('加载成功!'); })