title: Mapbox GL JS: Style is not done loading
body: <p>I have a map wher we can classically switch from one style to another, streets to satellite for example.</p>
  
  <p>I want to be informed that the style is loaded to then add a layer.</p>
  
  <p>According to the <a href="https://www.mapbox.com/mapbox-gl-js/api/#map.event:styledataloading" rel="noreferrer">doc</a>, I tried to wait that the style being loaded to add a layer based on a <code>GEOJson</code> dataset.</p>
  
  <p>That works perfectly when the page is loaded which fires <code>map.on('load')</code> but I get an error when I just change the style, so when adding layer from <code>map.on('styledataloading')</code>, and I even get memory problems in Firefox.</p>
  
  <p>My code is:</p>
  
  <pre><code>mapboxgl.accessToken = 'pk.token';
  var map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v10',
      center: [5,45.5],
      zoom: 7
  });
  
  map.on('load', function () {
  
      loadRegionMask();
  });
  
  map.on('styledataloading', function (styledata) {
  
      if (map.isStyleLoaded()) {
          loadRegionMask();
      }
  });
  
  $('#typeMap').on('click', function switchLayer(layer) {
      var layerId = layer.target.control.id;
  
      switch (layerId) {
          case 'streets':
              map.setStyle('mapbox://styles/mapbox/' + layerId + '-v10');
          break;
  
          case 'satellite':
              map.setStyle('mapbox://styles/mapbox/satellite-streets-v9');
          break;
      }
  });
  
  function loadJSON(callback) {   
  
    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
  
    xobj.open('GET', 'regions.json', true);
  
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 &amp;&amp; xobj.status == "200") {
            callback(xobj.responseText);
          }
    };
    xobj.send(null);  
  }
  
  function loadRegionMask() {
  
    loadJSON(function(response) {
  
      var geoPoints_JSON = JSON.parse(response);
  
      map.addSource("region-boundaries", {
        'type': 'geojson',
        'data': geoPoints_JSON,
      });
  
      map.addLayer({
          'id': 'region-fill',
          'type': 'fill',
          'source': "region-boundaries",
          'layout': {},
          'paint': {
              'fill-color': '#C4633F',
              'fill-opacity': 0.5
          },
          "filter": ["==", "$type", "Polygon"]
      });
    });
  }
  </code></pre>
  
  <p>And the error is: </p>
  
  <pre><code>Uncaught Error: Style is not done loading
      at t._checkLoaded (mapbox-gl.js:308)
      at t.addSource (mapbox-gl.js:308)
      at e.addSource (mapbox-gl.js:390)
      at map.js:92 (map.addSource("region-boundaries",...)
      at XMLHttpRequest.xobj.onreadystatechange (map.js:63)
  </code></pre>
  
  <p>Why do I get this error whereas I call <code>loadRegionMask()</code> after testing that the style is loaded?</p>