I want to append a script tag to the body of my HTML page. I added the following in my page:
<script type="text/javascript">
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);
}
window.onload = loadScript;
</script>
I tried to run it in JSFidle and there where no problems.
When I run it on my html page which runs on a demo server I get the following error in the console:
Uncaught TypeError: undefined is not a function
What causes this error and how can I prevent it?
Edit: Removing the type text/javascript does not change anything.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With