Asynchronous loading of the Google Maps API
I want to load an external JavaScript file using jQuery asynchronously and then call functions loaded from external JavaScript. I am including my JS file at the bottom of my html, before </html>
. The jQuery code is right before my code.
I am trying to do this:
(function(){
$(document).ready(function() {
obj.init();
});
var obj = {
init:function(){
$.ajax({
url: 'http://domain.com/script.js',
dataType: 'script',
success: function() {
obj.dostuff();
}
});
},
dostuff:function() {
// ...do stuff
}
}
window.obj = obj;
})();
The Chrome JavaScript Console reports this:
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 am trying to keep all my JS in one file, all in objects (classes and function types) and then call each class (function init()
) from $(document).ready();
.
What am I doing wrong here?
source to share
You can load the script using the following
var scriptElement = document.createElement('script');
scriptElement.src = "http://code.jquery.com/jquery-latest.min.js";
document.getElementsByTagName('head')[0].appendChild(scriptElement);
Then you can start using jQuery or any other library you have downloaded.
Or something similar
function loadMyScript() {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://code.jquery.com/jquery-latest.min.js";
document.body.appendChild(script);
}
window.onload = loadMyScript;
UPDATE:
(function(app, $, undefined) {
//public
app.init = function() {
var url = "//code.jquery.com/color/jquery.color.js";
$.getScript(url, function() {
doStuff();
});
};
//private
var doStuff = function() {
$(".block")
.animate({
backgroundColor: "rgb(255, 180, 180)"
}, 1000)
.delay(500)
.animate({
backgroundColor: "olive"
}, 1000)
.delay(500)
.animate({
backgroundColor: "#00f"
}, 1000);
};
}(window.app = window.app || {}, jQuery));
window.onload = app.init;
Here's the JsBin: http://jsbin.com/lumapubozu/1/edit?html,js,output
UPDATE GOOGLE MAPS
You just say in the link 'callback=app.loadMap'
what your callback is like.
(function(app) {
app.loadMap = function() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
};
app.loadGoogleMapsScript = function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
'callback=app.loadMap';
document.body.appendChild(script);
};
}(window.app = window.app || {}));
window.onload = app.loadGoogleMapsScript;
source to share