tshm
4/28/2011 - 12:41 PM

dynamic javascript loading

dynamic javascript loading

function loadScript(url, callback) {
	var tag = document.createElement('script');
	tag.type = 'text/javascript';
	tag.src = url;
	//tag.onreadystatechange = callback;
	tag.onload = callback;
	document.getElementsByTagName("head")[0].appendChild(tag);
};

function createXMLHttpRequest() {
	if (XMLHttpRequest) { // for NativeSupport
		return new XMLHttpRequest();
	} else { // for IE, use ActiveX
		try {
			return new ActiveXObject('MSXML2.XMLHTTP.6.0');
		} catch (e) {
			try {
				return new ActiveXObject('MSXML2.XMLHTTP.3.0');
			} catch (e) {
				try {
					return new ActiveXObject('MSXML2.XMLHTTP');
				} catch (e) {
					alert("no XMLHttp support available.");
				}
			}
		}
	}
}

function loadScript_sync(url) {
	var xhr = createXMLHttpRequest();
	xhr.open('GET', url, false);
	xhr.send('');
	// add the returned content to a newly created script tag
	var tag = document.createElement('script');
	tag.type = "text/javascript";
	tag.text = xhr.responseText;
	document.getElementsByTagName('head')[0].appendChild(tag);
}