Reputation: 33
I am dynamically loading Mapbox-GL JS in this way:
var script = domConstruct.create("script");
script.type = "text/javascript";
script.charset = "utf-8";
script.onload = instantiateMap();
script.src = "https://api.mapbox.com/mapbox-gl-js/v0.39.1/mapbox-gl.js";
script.async = false;
document.getElementsByTagName("head")[0].appendChild(script);
Then at some point, I am accessing it as follows in the 'instantiateMap' function:
mapboxgl.accessToken = 'pk.eyJ1IjoibW11a2ltIiwiYSI6ImNqNnduNHB2bDE3MHAycXRiOHR3aG0wMTYifQ.ConO2Bqm3yxPukZk6L9cjA';
var map = new mapboxgl.Map({
container: mapParent,
style: 'mapbox://styles/mapbox/streets-v9'
});
As soon as my control reaches the line (mapboxgl.accessToken...) it gives me the following error on Chrome Console:
Uncaught ReferenceError: mapboxgl is not defined
at Object._instantiateMap (VM2337 Sample.js:282)
_instantiateMap @ VM2337 Sample.js:282
This particular code snippet works fine in the following situations: - Including Mapbox-GL.js dynamically also works fine in an independent HTML file. - Including the library statically in the HTML files.
I know that the library loads fine because I see it in the left panel under Sources, but I have no idea as to why while accessing mapboxgl object, this error comes up.
Also I have tried including other libraries (jQuery, mapbox.js) in a similar fashion and they work fine.
Any help would be highly appreciated!
Upvotes: 1
Views: 7117
Reputation: 43
To solve this issue in express: In the response that is getting sent back, add the following
res.status(200).set(
'Content-Security-Policy',
'connect-src https://*.tiles.mapbox.com https://api.mapbox.com https://events.mapbox.com'
).render('whatever', {} );
Upvotes: 0
Reputation: 705
Without seeing the source code I can't test or fix the error.
My guess would be that the script is not loaded before the instantiation either because of the size of the script or the order of the code.
I would personally use a call back function for this to ensure instantiation only happens when the file has been fully downloaded (not tested)
JavaScript.load("https://api.mapbox.com/mapbox-gl-js/v0.39.1/mapbox-gl.js", function() {
mapboxgl.accessToken = 'pk.eyJ1IjoibW11a2ltIiwiYSI6ImNqNnduNHB2bDE3MHAycXRiOHR3aG0wMTYifQ.ConO2Bqm3yxPukZk6L9cjA';
var map = new mapboxgl.Map({
container: mapParent,
style: 'mapbox://styles/mapbox/streets-v9'
});
});
var JavaScript = {
load: function(src, callback) {
var script = document.createElement('script'),
loaded;
script.setAttribute('src', src);
if (callback) {
script.onreadystatechange = script.onload = function() {
if (!loaded) {
callback();
}
loaded = true;
};
}
document.getElementsByTagName('head')[0].appendChild(script);
}
};
Upvotes: 2