I'm using a JS promised based library (axios) to get a response from backend which returns a complete JS file. Once I receive this file how do I actually use it in my current page?
this the code:
axios.get('/foobar')
.then(jsFile => {
//use jsFile on current webpage
})
I have read some answers using eval()
, but I would prefer to avoid this method. Anyone has an idea how to proceed?
Make a script
tag with contents as jsFile
function addScriptToSession( jsFile )
{
var s = document.createElement('script');
s.type = 'text/javascript';
try {
s.appendChild(document.createTextNode(jsFile));
document.body.appendChild(s);
} catch (e) {
s.text = jsFile;
document.body.appendChild(s);
}
}
Use it as
axios.get('/foobar')
.then(jsFile => {
addScriptToSession(jsFile)
})