views:

53

answers:

2

My html page dynamically loads pages via Ajax for dynamic panels on the page. I need the script tags in the dynamically loaded pages to be executed. I fixed the code from a SO question. It works fine on FF/Safari/Chrome.

But dom nodes of type script work differently on IE. -- I can't seem to add text to a script node in IE 7:

//  variable "data" holds the script element's content from an
//  incoming html page loaded via ajax   
var script = document.createElement("script");        
script.type = "text/javascript";
script.appendChild(document.createTextNode(data)); // doesn't work on ie      

// also doesn't work on IE 7:
script.innerHTML = data;
script.innerText = data;

Any ideas for getting the sw to work on IE? (Other than using eval.)

+2  A: 

You should simple call eval(data).

Although it is true that eval should usually be avoided, this is one of the few exceptions.


EDIT: Without eval, you can do it like this:

    var scriptNode = document.createElement('script');
    scriptNode.type = 'text/javascript';
    scriptNode.text = data;
    document.head.appendChild(scriptNode); 
    document.head.removeChild(scriptNode); //Optional
SLaks
Is there any kind of formal reference explaining the `text` property of a script element? I can't seem to find this anywhere... Chrome has both script.text and script.textContent, I wonder if some browsers only have textContent?
no
I found a ref to text attribute here: http://msdn.microsoft.com/en-us/library/ms535892(v=VS.85).aspx But I wouldn't try it on a non-IE browser. The fact that appendChild doesn't work with IE 7 script nodes is the root bug.
Larry K
+2  A: 

You have a few options I can think of (other than using eval).

  • The script could be served from a separate path; setting the src of the script element instead of its content should work, even in IE.

  • The script to be executed could be attached to the onload listener of an image or other element, which can be appended to the document as you are doing with the script element.

  • use Function instead of eval. This will at least keep the evaluated code out of the local scope: new Function(data)();

no
+1 for the idea of directly adding/creating a function. Thanks.
Larry K