dimanche 4 décembre 2016

Code patterns for JavaScript libraries

Among JavaScript libraries (jQuery, MathJax, marked Markdown rendering library, etc.), I often see various patterns:

Pattern #1

index.html

...
<script src="mylibrary.js"></script>
</body>
</html>

mylibrary.js

var mylibrary = (function() {
    ...
    var myVar = ...
    ...
})();


Pattern #2

index.html

<html>
<head>
...
<script src="mylibrary.js"></script>
</head>
<body>
...
</body>
</html>

Same mylibrary.js


Pattern #3

index.html

<html>
<head>
...
<script src="mylibrary.js"></script>
</head>
<body>
...
<script>
mylibrary.run();    // explicitly needs to be run
</script>
</body>
</html>

Same mylibrary.js

Questions:

  1. What's the purpose of the var mylibrary = (function() { ... })(); trick?

  2. Is there a difference between pattern #1 and #2? (I would say no)

  3. Is there any reason to prefer #3 rather than #2?
    It seems that both could be interesting. Example for MathJax: pattern #2 makes sense (it would autoparse the DOM and render math formulas), it's what has been chosen by them (see this example). Pattern #3, requiring an action to actually run the rendering would make sense as well.

Aucun commentaire:

Enregistrer un commentaire