动态加载JS或CSS

动态加载JS,支持回调:

// 动态加载script标签内容

function loadScript(src, callback, charset) {

        var script = document.createElement('script');

        script.setAttribute('language', 'javascript');

	if (charset) {

	        script.setAttribute('charset', charset);

	}

	script.setAttribute('src', src);

	document.getElementsByTagName("head")[0].appendChild(script);

	if(document.all) {

		script.onreadystatechange = function() {

			if(this.readyState == 4 || this.readyState == 'complete' || this.readyState == 'loaded') {

				callback();

			}

		};

	} else {

		script.onload = function() {

			callback();

		};

	}

}

 动态加载JS和CSS集合:

/*

 * o的结构 {js:['a.js'],css:['a.css'],callback:function(){}}

 */

Common.jsCssLoadRun = function(o) {

	var count = 0;

	var scriptTag, linkTag;

	var scriptFiles = o.js;

	var cssFiles = o.css;

	var head = document.getElementsByTagName('head')[0];



	for ( var k = 0; k < cssFiles.length; k++) {

		linkTag = document.createElement('link');

		linkTag.type = 'text/css';

		linkTag.rel = 'stylesheet';

		linkTag.href = cssFiles[k];

		head.appendChild(linkTag);

	}



	for (k = 0; k < scriptFiles.length; k++) {

		scriptTag = document.createElement('script');

		scriptTag.type = 'text/javascript';

		scriptTag.charset = 'utf-8';

		scriptTag.src = scriptFiles[k];

		head.appendChild(scriptTag);

		if (typeof o.callback == "function") {

			if (scriptTag.readyState) { // IE

				scriptTag.onreadystatechange = function() {

					if (scriptTag.readyState == "loaded"

							|| scriptTag.readyState == "complete") {

						count++;

						if (count == scriptFiles.length)

							o.callback.call();

					}

				};

			} else { // other browsers

				scriptTag.onload = function() {

					count++;

					if (count == scriptFiles.length)

						o.callback.call();

				};

			}

		}

	}



	if (scriptFiles.length == 0) {

		o.callback.call();

	}

};

 多浏览器支持情况,可参考这里

你可能感兴趣的:(css)