假设我通过两个网站使用谷歌地图api
<head>
<script
src="https://maps.googleapis.com/maps/api/js?sensor=false&hl=zh-CN&v=3.21&callback=initMap" async defer>
</script>
<script
src="http://ditu.google.cn/maps/api/js?sensor=false&hl=zh-CN&v=3.21&callback=initMap" async defer>
</script>
</head>
<body>
<script>
function initMap() {
//something
}
</script>
</body>
有时我无法连接到第一个网站,但代码仍然有效。现在我想在每次连接时使用第一个站点。有没有办法设置两个站点的优先级?
答案 0 :(得分:3)
您可以使用document.createElement
使用javascript加载第一个,并添加onerror
事件处理程序,如果第一个失败,则将src
设置为第二个来源:
<script>
var script = document.createElement('script');
script.src = 'http://ditu.google.cn/maps/api/js?sensor=false&hl=zh-CN&v=3.21&callback=initMap';
script.onerror = function() {
// if the above source fails to load, try this one
this.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&hl=zh-CN&v=3.21&callback=initMap';
this.onerror = function() {
console.log('Nothing loaded!');
}
}
script.async = true;
script.defer = true;
document.body.appendChild(script);
</script>