Attach ajax content and execute scripts in it


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /**
  2. * attach_and_execute_scripts helper function
  3. * Copyright (c) 2010 by Anders Ytterström <http://madr.se>
  4. * Released under the MIT license.
  5. *
  6. * Description:
  7. * A light-weight function to extract and execute SCRIPT from
  8. * an ajax response. it also attach the new content to the DOM
  9. * tree.
  10. */
  11. function attach_and_execute_scripts(wrapper_elm, ajax_response, create_target) {
  12. var target_elm;
  13. var extracted_scripts;
  14.  
  15. extracted_scripts = (function (tmp_elm) {
  16. tmp_elm.innerHTML = ajax_response;
  17.  
  18. var refs = [], scr = tmp_elm.getElementsByTagName('script');
  19.  
  20. for (var i = 0, max = scr.length; i < max; i++) {
  21. refs.push(scr[i].cloneNode(true));
  22. }
  23.  
  24. return refs;
  25. })(document.createElement('div'));
  26.  
  27. // will prevent Gecko from executing scripts twice
  28. cleaned_markup = ajax_response
  29. .replace(/<script[^>]*>[nsS]*?</script>/img, '');
  30.  
  31. target_elm = create_target(cleaned_markup);
  32. wrapper_elm.appendChild(target_elm);
  33.  
  34. // caution: document.write will break the page!
  35. if (extracted_scripts) {
  36. for(var i = 0, max = extracted_scripts.length; i < max; i++) {
  37. target_elm.appendChild(extracted_scripts[i]);
  38. }
  39. }
  40. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.