I want to append a script tag to the body of my HTML page. I added the following in my page:
The error you are getting is because there is no initialize()
function. If you declare one there will be no error.
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize';
document.body.appendChild(script);
console.log('loadScript');
}
function initialize() {
console.log('initialize');
}
window.onload = loadScript;
I tried to run it in JSFidle and there where no problems.
Incorrect. On JSFiddle you have a different problem.
There you run your code when the document load event fires. That code defines a function and assigns an event handler for the document load event. Since that event has already fired, the function never runs. You don't get an error because the code doesn't get as far as it does when you test in your standalone document.
When I run it on my html page which runs on a demo server I get the following error in the console:
In this case, the code is running successfully.
The load event fires. The loadScript function runs. The script element is appended to the page. Google's script runs.
You get an error because you said:
'callback=initialize'
So the script you are requesting from Google tries to call initialize()
, but you haven't defined that function so you get an error instead.
See also the documentation which includes this example:
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
'&signed_in=true&callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;