动态脚本

使用js可以动态的为html添加脚本

动态脚本

var sc=documet.createElement("script");

sc.type="text/javascript"

sc.src="a.js"

var top=document.head

top.appendChild(sc)

先创建一个script标签,然后为标签添加属性,最后将标签添加到head中,便创建成功了一个动态脚本

此外,还有另一种方式

对于非IE浏览器

var sc=documet.createElement("script");

sc.type="text/javascript"

sc.appendChild(document.createTextNode("function(){alert(\"a\")}"))//为script添加子文本节点,相当于直接写script标签中的内容

var top=document.head

top.appendChild(sc)

对于IE浏览器

IE浏览器不允许为script标签添加节点

所以在IE中

var sc=documet.createElement("script");

sc.type="text/javascript"

sc.Text="function(){alert(\"a\")}"//为script添加子文本节点,相当于直接写script标签中的内容

var top=document.head

top.appendChild(sc)

所以想要兼容两种浏览器需要下面的写法

var code="function(){alert(\"a\")}";

var top=document.head

var sc=documet.createElement("script");

try

{

sc.appendChild(document.createTextNode(code))

}

catch(ex)

{

sc.Text=code;

}

top.appendChild(sc);

 

posted @ 2016-09-21 11:27  shenlong77  阅读(185)  评论(0编辑  收藏  举报