31
votes

I will provide more information to explain my situation. I am building an application with PhoneGap for deployment on iOS. I have a a view/page that user will navigate to (not using ajax) that will load google maps js scripts that are needed and do a call to the cordova geolocation api.

My issue is that loading the google maps script:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXX&sensor=true"></script>

Takes too long to load and stops the page from rendering for up to almost 3 seconds. I want to defer the load of the external script until the page has fully rendered. Putting the script down at the bottom of the page just before does not help at all.

I was attempting to use getScript() but it will not work and throws the following error in debug console:

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.

I have tried 'defer' and 'async' in the actual script tag, but that throws the same error as well. Other methods of loading external JS files lands me with the same error message.

Is there any possible workaround to this problem. I don't even know what the error statement means...

4
-1? That was a bit harsh. Anyone want to volunteer further information for the reason behind that? @geocodezip, I have already tried doing what you suggested. In fact I have tried several methods but they don't work. I have figured out the core issue, the remote google api script I am loading is in fact loading another script, so yeah I can't call a script asynchronously that is calling another script asynchronously. Will post solution as soon as I get it.Ryan Coolwebs
Read the documentation once more, there is a callback-parameter, you be able to load the API asynchronously and call it(run the function defined as callback ) when it's ready to use.Dr.Molle
Ok, yeah I got it now. I fiddled around with it some more and just put an empty function for callback (as I don't want to run any function on callback). A button loads the map and location.Ryan Coolwebs
You'd probably better remove API key from your code sample in question.Paul Kozlovitch

4 Answers

13
votes

I tried this solution of mine and it worked.

Run the script on dom ready using jquery.

basically instead of using your function initialize like this :

function initialize(){
/*You code */
}

do this:

$(function(){
/*You code */
})

And no need for google.maps.event.addDomListener(window, 'load', initialize);

Anymore.


Edit #1 : I am currently facing some familiar problem to yours, and I think I have a better solution to you now.

in your JS file, after your initialize function , put this function:

var ready: // Where to store the function

    ready = function() {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' + 'libraries=places&'+'callback=initialize';
      document.body.appendChild(script);
    };

What it basically does is that it calls for the map loader first, and then calls for the map after the loader is ready.
And afterwards make use of you what just wrote with this

In your html page :

<script>
    $.getScript("You js file path",function(){
          $(document).ready(ready);
    });
</script>

And this gets the script so you can use its variables, and then call the variable you need ready after the DOM is ready and finished loading.

I recommend putting this at the bottom of your html page,after the body closes.

4
votes

I was trying to load google maps in a partial view that would load as a standard page (which wasn't the problem) or a bootstrap modal and having no luck with this error (for the modal):

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.

I'm not using scripts because I'm dynamically calling the markers from my data model (or I at least I haven't gotten that far yet). Anyway, thanks to Hamza, I was able to get it working with this:

<div id="map-canvas" style="width:512px;height:464px;"></div>

@*<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>*@
    <script type="text/javascript">
    function initialize() {
        var mapDiv = document.getElementById('map-canvas');

        var mapOptions = {
            zoom: 1,
            minzoom: 1,
            mapTypeControl: true,
            zoomControl: true,
            scaleControl: true,
            streetViewControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        var map = new google.maps.Map(mapDiv, mapOptions);

        //var markers = getMarkers(map);
        map.setCenter({ lat: 0, lng: 0 });

    };

    //google.maps.event.addDomListener(window, 'load', initialize);
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&callback=initialize';
    document.body.appendChild(script);
</script>

One more thought, I had to remove the fade from my modal as well which correlates to someone else commenting they had to delay the execution by a second. I tried the resizetarget fix and all that with no luck as well.

Lots of trial and error on this one, hopefully saves someone some time.

3
votes

//Using jQuery's getScript function

$.getScript('[js containing the initialize function]',function(){
    $.getScript('https://maps.googleapis.com/maps/api/js?v=3.exp&callback=initialize');
}); 

Explanation:

First load your external script containing the initialize function and upon callback, load the google map API with callback equals to initialize.

-2
votes

You need to load the js file after the body tag end.