且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

附加<脚本>贴到身体?

更新时间:2023-12-05 17:50:10

你得到的错误是因为没有 initialize()函数。如果你申报一个就没有错误。

  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');
}

函数initialize(){
console.log('initialize');
}

window.onload = loadScript;


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;