如何实现JavaScript动态加载CSS和JS文件

html-css014

如何实现JavaScript动态加载CSS和JS文件,第1张

动态加载外部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 )

}

}

如果是的话,直接放到一个DIV里面是错误的。

就算内容可以显示也只是浏览器的兼容性做得比较好。要把里面的CSS给添加到当前页面的话,不应该采用这种做法。你需要的是在当前页面添加<link>标签去动态加载这个CSS文件。

Ajax请求应该只返回少量的数据。