附加<脚本>贴到身体? [英] Append <Script> Tag to Body?

查看:89
本文介绍了附加<脚本>贴到身体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的HTML页面的主体上添加一个脚本标记。我在页面中添加了以下内容:

 < script type =text / javascript> 

函数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>

我试图在



什么原因这个错误以及如何防止它?



编辑:删除类型text / javascript不会改变任何内容。

解决方案

你得到的错误是因为没有 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;

这篇关于附加&lt;脚本&gt;贴到身体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆