Dynamic JavaScript via Ajax and innerHTML

I may be shot down for this for bad design or evil JavaScript usage, but nevertheless...consider the following architecture:
  • You have a complex page that drives a lot of functionality via Ajax.
  • Clicking on a 'Create User' link for example will perform an async call on a back-end create-user HTML widget and display this content in a div panel.
  • The create-user widget is self-contained, i.e. it's a mixture of HTML and JavaScript.
  • The JS portion of create-user is responsible for driving validation logic and perhaps making other Ajax calls.
So how do you implement this? Simply retrieving the mixed create-user content and sticking it in a div's innerHTML property won't work as the retrieved content is just text and the <script> tags won't be parsed by the browser or added to the DOM, meaning all the JS is inaccessible. To get things working you need to do this yourself as follows:

//ajax call to get create-user content as rsp
div = document.getElementById('targetDiv').innerHTML = rsp;

function evalScript(div) {
var x = div.getElementsByTagName("script");
var scriptBlocks = [];

for(var i=0; i<x.length; i++)
//append the script to the div body,
//note that simply doing an eval() would not work as the script would not be stored in the DOM
var oScript = document.createElement('script');
oScript.text = x[i].text;
scriptBlocks[i] = oScript;

//we could have added the scripts to the div directly above, but then we'd trigger an infinite loop
for(var i=0; i <scriptBlocks.length; i++) {

I've tested this in Google Chrome and it seems to work. Not sure about IE, FF, Opera, Safari...but fingers crossed. Also, if anyone knows of a reason why this is really bad, please let me know!


Popular posts from this blog

Wkhtmltopdf font and sizing issues

Import Google Contacts to Nokia PC Suite

Can't delete last blank page from Word