Question

I'm using Google Maps API V3 in a .js file loaded by turbolinks.

The map rendering is triggered when the $('#google-map') element is loaded:

function initGoogleMap() {
   ...
   var map = new google.maps.Map($('#google-map').get(0), mapOptions);
   ...
}

$('#google-map').ready(function() {
  initGoogleMap();
});

The problem is that when initGoogleMap() runs, it uses the width and height of $('#google-map') to render the map, and at this point the width and height are 0.

The width and height are defined in a .scss file named after the controller:

.map {
    height: 300px;
    width: 400px;

    #google-map {
        height: 300px;
        width: 400px;
    }
}

I'm using rails' conventions, so in my view template there is no mention of either the .js filename or the .scss filename.

How can I make sure the script only runs after the stylesheet is loaded?

Was it helpful?

Solution

Part 1: Page specific JS:

Check out one possible solution to page-specific JS in the rails pipeline here: https://stackoverflow.com/a/11975103/1162491

Part 2: Running JS after CSS rules are applied:

I'm assuming that your CSS is loaded in the <head> of your application layout. At the bottom of your template, include the page-specific javascript with javascript_include_tag and have your javascript load when the document is ready. This should resolve your issues; however, as this SO post shows, placing the stylesheet tags before your javascript tags may not always result in the expected behavior, since CSS is loaded async. So, as one answer in that post suggests,

$(window).load(function() { $('#abc')...} ); 

might consistently perform better than $(document).ready().

OTHER TIPS

As the jquery's ready() function explains(http://api.jquery.com/ready/),

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

so use load() method may solves your problem.

$('#google-map').load(function() {
  initGoogleMap();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top