There are several approaches to solve this problem. I am not sure how your js is related to the template file that you mentioned, but the following answers apply if you want to execute a JS file received as response of a XHR Request.
Sol 1 using Eval:
xhr.onreadystatechange = function(){
if( xhr.readyState === 4 ){
eval ( xhr.responseText );
}
}
Sol 2 using dynamic injection
xhr.onreadystatechange = function(){
if ( xhr.readystate === 4 ){
var head = document.getElementsByTagName("HEAD")[0];
var script = document.createElement("SCRIPT");
script.text = xhr.responseText;
head.appendChild(script);
}
}
This will create a script element in the head and set it text to the AJAX response. With this, your JS will be parsed but wont be executed. If you want it to execute instantly, you can deliberately call it in the last line in the response like this:
//JS that you fetch
function A(){
}
// call A here so that it executes when this script is injected.
A()
The only problem with the above solutions is the same domain restriction that XHR brings to you. If you want to include scripts dynamically from different domains, you can use something even simpler:
var scr = document.createElement("SCRIPT");
scr.src = "dynamically set this to the external script source"
document.getElementsByTagName("HEAD")[0].appendChild(scr);
There are other approaches like the IFRAME approach as mentioned by other responses.