var new_element = document.createElement("script")//创建新的script节点new_element.setAttribute("type", "text/javascript")new_element.setAttribute("src", "../js/jquery.js")document.body.appendChild(new_element)//添加到body节点的末尾
上例中是在body的最末尾添加的,当然同样可以在head中添加引用该js的标签:document.head.appendChild(new_element)
1、直接document.write<script language="javascript">
document.write("<script src='test.js'><\/script>")
</script>
2、动态改变已有script的src属性
<script src='' id="s1"></script>
<script language="javascript">
s1.src="test.js"
</script>
3、动态创建script元素
<script>
var oHead = document.getElementsByTagName('HEAD').item(0)
var oScript= document.createElement("script")
oScript.type = "text/javascript"
oScript.src="test.js"
oHead.appendChild( oScript)
</script>
其实原理就是利用dom动态的引入一个js到文件中来~就能和原有的js通信了~
动态加载外部css样式及css样式,参考代码如下:
// 动态加载外部js文件var flag = true
if( flag ){
loadScript( "js/index.js" )
}
function loadScript( url ){
var script = document.createElement( "script" )
script.type = "type/javascipt"
script.src = url
document.getElementsByTagName( "head" )[0].appendChild( script )
}
// 动态加载js
if( flag ){
var script = document.createElement( "script" )
script.type = "text/javascript"
script.text = " "
document.getElementsByTagName( "head" )[0].appendChild( script )
}
// 动态加载外部css样式
if( flag ){
loadCss( "css/base.css" )
}
function loadCss( url ){
var link = document.createElement( "link" )
link.type = "text/css"
link.rel = "stylesheet"
link.href = url
document.getElementsByTagName( "head" )[0].appendChild( link )
}
// 动态加载css样式
if( flag ){
var style = document.createElement( "style" )
style.type = "text/css"
document.getElementsByTagName( "head" )[0].appendChild( style )
var sheet = document.styleSheets[0]
insertRules( sheet,"#gaga1","background:#f00",0 )
}
function insertRules( sheet,selectorTxt,cssTxt,position ){
if( sheet.insertRule ){ // 判断非IE浏览器
sheet.insertRule( selectorTxt + "{" + cssTxt +"}" ,position )
}else if( sheet.addRule ){ //判断是否是IE浏览器
sheet.addRule( selectorTxt ,cssTxt ,position )
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)