Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append <Script> Tag to Body?

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

enter image description here

What causes this error and how can I prevent it?

Edit: Removing the type text/javascript does not change anything.

like image 891
confile Avatar asked Dec 02 '22 16:12

confile


1 Answers

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;
like image 198
Tasos K. Avatar answered Dec 07 '22 23:12

Tasos K.