Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modules in Javascript with eval();

Every javascript developer knows; eval is evil

But since i am looking for the ultimative module technology in javascript, i read something very interesting about someone using eval as a module loader, which has 2 main benefits:

  • Faster loading for mobile, because its loading a whole string at once
  • Script seperating without doing fancy define wrappers like require.js in each module

So whats all about that? And could it be a solution, to only load several functions through eval? I mean from security aspects...

Edit: sry forgot the link to the article: Article

like image 212
David Fariña Avatar asked Mar 24 '23 01:03

David Fariña


1 Answers

Because of the high-latency on 3G connections a single HTTP request, even with more data, is often a lot faster then multiple smaller requests.

What that article proposes is combining multiple modules into one file like this:

var modules = {
    'main.js': 'alert("Main module")',
    'another.js': 'alert("Another module")',
    'notUsed.js': 'alert("I am never used")',
};

That way they can all be downloaded with a single HTTP request which is faster, and you can still only include/evaluate the modules you need.

e.g. you could do:

var requireFile = function(file) {
    if(modules[file])
        eval(modules[file]);
};

requireFile('main.js');
requireFile('another.js');

and only main.js and another.js would be evaluated, notUsed.js would just be ignored.

Security wise, it shouldn't be any different to including them via the <script> tag provided whatever you use to combine the scripts can't accidentally combine/include other files/strings too.

So from a security perspective, there shouldn't any difference from the above and this:

<script src="main.js"></script>
<script src="another.js"></script>

Of course you still have the other disadvantages of eval.

like image 157
Sam Avatar answered Apr 01 '23 10:04

Sam