Loading google maps asynchronously

前端 未结 2 1487
深忆病人
深忆病人 2020-12-03 15:36

I am trying to load my google map asynchronously and it works but it is loading the map in twice. If I remove \"box.onload = initialize;\" this stops that probl

相关标签:
2条回答
  • 2020-12-03 16:32

    The map appears twice because you're calling initialize twice.

    Before fixing that, let's simplify your code a bit. Never let yourself repeat blocks of code like that; instead make it into a common function.

    Also, don't load infobox.js from googlecode.com; Google Code is not a CDN. Load your own copy.

    So, the code may look like this:

    function addScript( url, callback ) {
        var script = document.createElement( 'script' );
        if( callback ) script.onload = callback;
        script.type = 'text/javascript';
        script.src = url;
        document.body.appendChild( script );  
    }
    
    function loadMapsAPI() {
        addScript( 'https://maps.googleapis.com/maps/api/js?key=key_goes_here&sensor=false&callback=mapsApiReady' );
    }
    
    function mapsApiReady() {
        addScript( 'infobox.js', initialize );
    }
    
    window.onload = loadMapsAPI;
    
    0 讨论(0)
  • 2020-12-03 16:33

    I created this script. You can call this and add any callback function, so you have to just include this to your scripts and call

    googleMapsLoadAsync(function(){ alert('google maps loaded'); });

    script

    var googleMapsAsyncLoaded = false;
    var googleMapsAsyncCallback = function(){ };
    
    function googleMapsLoadAsync(callback) {
    
        if (typeof callback !== 'undefined') { googleMapsAsyncCallback=callback; }
    
        if(!googleMapsAsyncLoaded) {
    
            $.getScript('https://maps.googleapis.com/maps/api/js?sensor=false&async=2&callback=googleMapsAsyncLoadedFunction');
    
        } else {
    
            googleMapsAsyncLoadedFunction();
    
        }
    
    }
    
    function googleMapsAsyncLoadedFunction() {
    
        googleMapsAsyncLoaded = true;
    
        if(googleMapsAsyncCallback && typeof(googleMapsAsyncCallback) === "function") {
    
            googleMapsAsyncCallback();
    
        }
    
        googleMapsAsyncCallback = function(){ };
    
    }
    
    0 讨论(0)
提交回复
热议问题