17
Mar/09
0

JavaScript in innerHTML

In some scripts I need to load mixed HTML and JavaScript code via ajax and assign it to a parsed divs innerHTML. The JavaScript code is only executed by the Firefox (3.x). All other browsers I tested (IE7 and Opera 9.x) do not execute the JavaScript code. In most cases the JavaScript code is written directly in a simple <script> tag. In some cases the fetched code contains script tags which refer to new javascript files. I built some code to workaround this problem…

I can access the <script> tags via DOM in all browsers so I built the following workaround to get the JavaScript code executed:

var oObj = document.getElementById('container');
oObj.innerHTML = "<script>alert('test');</script>";
evalJSinInnerHTML(oObj);
oObj = null;
 
function evalJSinInnerHTML(oObj) {
	if(!navigator.userAgent.indexOf("Firefox") > -1) {
		var aScripts = oObj.getElementsByTagName('script');
		for(var i = 0, len = aScripts.length; i < len; i++) {
			if(aScripts[i].src && aScripts[i].src !== '') {
				var oScr = document.createElement('script');  
				oScr.src = aScripts[i].src;  
				document.body.appendChild(oScr);
				oScr = null;
			} else {
				try {
					eval(aScripts[i].text);
				} catch(e) {
					alert("Problem executing: "+aScripts[i].text);
				}
			}
		}
	}
	oObj = null;
}

This function also handles javascript file inclusions by creating script elements and appending them to the body.

Filed under: Javascript
Comments (0) Trackbacks (0)

No comments yet.

No trackbacks yet.