0

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?

CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186

1 Answers1

3

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)     
  })
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Cool but how is this any different than `eval`..? – Redu Mar 28 '18 at 15:01
  • 1
    @Redu with eval you can't use properly the debugger. Every call to eval() produces a new instance of the JS interpreter. https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – CommonSenseCode Mar 29 '18 at 09:29