2

In an app I'm debugging, a previous developer appears to be relying on underscore.js to do a couple things.

I keep intermittently getting "_ is undefined" errors in my browser console, preventing chunks of the app from running correctly.

The underscore library eventually appears to load, since I'm able to do console.log(_) in my browser and get a giant object as a result, once the page has fully loaded.

My question is this: Is there a preferred way to wrap functions that rely on underscore? (In other words, do underscore developers often use something similar to the old practice of wrapping a bunch of logic inside $(function(){...}) in order to make sure that it runs after jQuery is loaded?)

  • Is loading underscorejs as the first script the page can load an option? I ask that since underscore doesn't depend on any other js libraries and its a minimal script that doesn't take long to load, so you should be fine loading it first up. – Winter Soldier Jul 18 '17 at 13:51

1 Answers1

0
  • Is this script any closer to what you are looking for? I used the script loader from here

  • It loads the given list of scripts and gives you a callback handle where you may invoke the dependent js functions

<html>

<head>
  <script type='text/javascript'>
    function loadScripts(array, callback) {
      var loader = function(src, handler) {
        var script = document.createElement("script");
        script.src = src;
        script.onload = script.onreadystatechange = function() {
          script.onreadystatechange = script.onload = null;
          handler();
        }
        var head = document.getElementsByTagName("head")[0];
        (head || document.body).appendChild(script);
      };
      (function run() {
        if (array.length != 0) {
          loader(array.shift(), run);
        } else {
          callback && callback();
        }
      })();
    }

    loadScripts([
      "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"
    ], function() {
      console.log(_);
      var arr = ['jQuery', 'underscore', 'jasmine'];
      _.each(arr, (val) => {
        console.log(val);
      });
    });
  </script>
</head>

<body>

</body>

</html>
Winter Soldier
  • 2,607
  • 3
  • 14
  • 18