With all the challenges of XSS, most often your goal is to prevent unintentional script execution. Ironically, getting dynamically injected scripts to run when you want them to can be as hard as preventing those that you don’t want to.
Depending on your scenario, this might now be too hard. jQuery takes care of doing this for you when you add HTML via its methods, such as $(...).html(...). jQuery actually parses the HTML itself, identifies, script blocks, and executes them via eval(...). The problem comes in for scripts with an src attribute, rather than an inline script.
jQuery loads script tags with ansrc attribute via AJAX, and then executes them. This is fine if the script is located on your servers, but in my case the scripts were hosted on 3rd party sites, and the servers weren’t setup for cross-domain requests.
My final solution was based on this this StackOverflow question. I injected the HTML using the raw DOM APIs, then executed a helper function on that node to go back and execute the scripts. My modified version of the StackOverflow answer is below, which handles the case for src attributes on the scripts.