代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>异步加载地图</title>
<style>
body,
html {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
font-family: '微软雅黑';
}
#background {
height: 100%;
width: 100%;
position: absolute;
background: #eee;
color: #666;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
#map {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="background">点击后异步加载地图</div>
<div id="map"></div>
<script>
function loadJScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://api.map.baidu.com/api?v=4.0&ak=您的密钥&callback=init';
document.body.appendChild(script);
}
function init() {
var map = new BMap.Map('map'); // 创建Map实例
var point = new BMap.Point(116.404, 39.915); // 创建点坐标
map.centerAndZoom(point, 10);
map.enableScrollWheelZoom(); // 启用滚轮放大缩小
}
document.getElementById('background').addEventListener('click', function () {
loadJScript(); // 异步加载地图
});
</script>
</body>
</html>
加载的入口脚本通过callback属性实现异步回调
预览