从外部js脚本创建元素并插入到html中

时间:2015-03-11 11:58:01

标签: javascript dom

我正在尝试创建一个小部件。像google-adsense块之类的东西,所以我需要从页面的不同位置调用相同的脚本。是否可以在外部js脚本中创建一个元素并将其插入我调用脚本的地方?

我这样做:

<div><script type="text/javascript" src="loader.js"></div>
<div><script type="text/javascript" src="loader.js"></div>

Loader.js:

var div = document.createElement('div');
div.setAttribute('class', 'inner-div');
document.body.appendChild(div);

我有:

<div><script type="text/javascript" src="loader.js"></div>
<div><script type="text/javascript" src="loader.js"></div>
<div class="inner-div"></div>
<div class="inner-div"></div>

但我想得到这个结果:

<div>
    <script type="text/javascript" src="loader.js">
    <div class="inner-div"></div>
</div>
<div>
    <script type="text/javascript" src="loader.js">
    <div class="inner-div"></div>
</div>

1 个答案:

答案 0 :(得分:0)

我想我找到了解决方案。查找当前脚本标记:

<div>
<script type="text/javascript">
  var scripts = document.getElementsByTagName('script');
  var script = scripts[scripts.length - 1];
  loadScript('loader.js', function () {
    loader().init({script: script});
  });
</script>
</div>

loadScript函数:

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

然后在loader.js中:

init: function(args) {
...
var div = document.createElement('div');
div.setAttribute('class', 'inner-div');
args.script.parentNode.appendChild(div);
...
}