执行的javascript的优先级

时间:2016-08-27 07:02:22

标签: javascript google-maps-api-3

假设我通过两个网站使用谷歌地图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>

有时我无法连接到第一个网站,但代码仍然有效。现在我想在每次连接时使用第一个站点。有没有办法设置两个站点的优先级?

1 个答案:

答案 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>