0

guys!

I decided to write own module loader. For example, I have 2 js files, and one of them try to load and execute other one.

I used XMLHttpRequest, where as action-argument I send the path to file, and when I get response I execute xhr.responseText by eval() method.

Is this solution correct? Or it is architectural incorrect?

  • All the module loaders I know are open-source. I'd suggest you to have a look. And no, eval isn't needed. – Denys Séguret Nov 18 '14 at 12:58
  • should create a new script tag and set the content with your loaded js – Hacketo Nov 18 '14 at 13:01
  • 1
    Did you search for similar questions? -- [site:stackoverflow.com javascript load javascript](https://www.google.com/search?q=site:stackoverflow.com%20javascript%20load%20javascript) – Nabil Kadimi Nov 18 '14 at 13:01
  • eval() ensures that the given script has run completely before continuing as far as I know. If you don't require the functions loaded immediately then you can use dynamic script tags to append the script with their respective filenames. This will also solve cross-domain issues which you'd get with XMLHttpRequest. To be sure that the functions loaded and interpreted by the browser there are many different approaches... – Ali Naci Erdem Nov 18 '14 at 13:03

1 Answers1

0

Function eval() is one of the most evil things in javascript. It's makes your code unsecuriry and a lot of other bad things. You can read about it here

So I think on of the good solution for it makes function like that:

function loadScript(url)
{
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Fire the loading
    head.appendChild(script);
}

And you can execute this script loadScript('my_js_file.js');

Alex Filatov
  • 2,232
  • 3
  • 32
  • 39
  • Update: ES6 natively supports modules. Or, use a module system or loader library such as RequireJS. ([More details here.](http://stackoverflow.com/a/29181416/3345375)) – jkdev Jun 27 '16 at 21:01
  • And I agree that `eval` should be avoided. There's a reason Douglas Crockford calls it one of the "[Bad Parts](http://archive.oreilly.com/pub/a/javascript/excerpts/javascript-good-parts/bad-parts.html)" of JavaScript. – jkdev Jun 27 '16 at 21:02