异步加载谷歌地图 API

Asynchronous Loading Google Maps API

本文关键字:API 谷歌地图 加载 异步      更新时间:2023-09-26

>我想使用 jQuery 异步加载一个外部 JavaScript 文件,然后能够调用从外部 JavaScript 加载的函数。我将我的 JS 文件包含在 html 的底部,就在 </html> 之前。jQuery代码在我的代码之前。

我正在尝试这个:

(function(){
    $(document).ready(function() {
        obj.init();
    });
    var obj = {
        init:function(){
            $.ajax({
                url: 'http://domain.com/script.js',
                dataType: 'script',
                success: function() {
                    obj.dostuff();
                }
            });
        },
        dostuff:function() {
            // ...do stuff
        }
    }
    window.obj = obj;
})();

Chrome JavaScript 控制台报告了以下内容:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

我试图将所有JS保存在一个文件中,全部保存在对象(类和函数样式)中,然后从$(document).ready();中调用每个类(init()函数)。

我在这里做错了什么..?

可以使用以下命令加载脚本

var scriptElement = document.createElement('script');
scriptElement.src = "http://code.jquery.com/jquery-latest.min.js";
document.getElementsByTagName('head')[0].appendChild(scriptElement);

然后你可以开始使用jQuery或任何你加载的库。

或类似的东西

function loadMyScript() {
  var script = document.createElement('script');
  script.type = "text/javascript";
  script.src = "http://code.jquery.com/jquery-latest.min.js";
  document.body.appendChild(script);
}
window.onload = loadMyScript;

更新:

(function(app, $, undefined) {
  //public
  app.init = function() {
    var url = "//code.jquery.com/color/jquery.color.js";
    $.getScript(url, function() {
      doStuff();
    });
  };
  //private
  var doStuff = function() {
    $(".block")
      .animate({
        backgroundColor: "rgb(255, 180, 180)"
      }, 1000)
      .delay(500)
      .animate({
        backgroundColor: "olive"
      }, 1000)
      .delay(500)
      .animate({
        backgroundColor: "#00f"
      }, 1000);
  };
}(window.app = window.app || {}, jQuery));
window.onload = app.init;

这是 JsBin: http://jsbin.com/lumapubozu/1/edit?html,js,output

谷歌地图更新

您只需在链接中说'callback=app.loadMap'您的回调是什么。

(function(app) {
      app.loadMap = function() {
        var mapOptions = {
          zoom: 8,
          center: new google.maps.LatLng(-34.397, 150.644)
        };
        var map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);
      };
      app.loadGoogleMapsScript = function () {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
          'callback=app.loadMap';
        document.body.appendChild(script);
      };
    }(window.app = window.app || {}));
    window.onload = app.loadGoogleMapsScript;

斌: http://jsbin.com/wigoxarayu/1/edit?js,output