Back to the Konsensys

Back to Tips
Loading and Executing JavaScript via AJAX
by
George Van Treeck

New JavaScript loaded into a web page via AJAX will not be executed! The following technique will allow you to get that newly loaded JavaScript executed:

First, define a JavaScript function that gets the the contents of your script and executes it.

 function execute_new_javascript() {
   my_script_element = document.getElementById('my_script');
   if (typeof(my_script_element) == 'undefined' ||
       my_script_element == null)
     return;
   my_script_text = my_script_element.innerHTML;
   eval(my_script_text);
 }

Second, have your server-side code send new JavaScript with the specified id, my_script, as part of the AJAX response.

Finally, after every use of AJAX call the above, execute_new_javascript(), function.


To see complete example in use. You can go the website, BestPicker website and view the source HTML.


Copyright (C) 2010 George Van Treeck. All rights reserved.