Underscore.js boot detection

This is a border issue, but I decided it was worth it. Below is the most concise way to check if underscore.js is loaded , and if there are any return paths for this approach.

typeof _  == "function" ? console.log('yes') : console.log('no');

Honestly, my "real" question is this. This is mainly a plugin that will be used on many front-end platforms. Some will underscore, and some will not. To make it universal and use the methods provided underscore, I want to check underscoreand provide a backup, if not, when choosing to use, when I can.

Is this a bad practice, and I should not even worry about using underscores when it is present?

NOTE. Unfortunately, lodash.jsthis is not an option, because I stupidly remade it underscore.jsinto the configuration require, and people do not seem to understand the need for AMD-compatible modules.

+4
source share
2 answers

Given that Underscore is exported as a function, it can be said that performing type checking is the shortest way to check for Underscore's availability in memory. If I get it right - for some strange reason, I have to say - you want to implement a function check, so contexts that do not have concrete method implementations will elegantly get worse.

Underscore . Underscore, , :

if(typeof _ === 'function') {
  if(typeof _.reduce !== 'undefined') {
    // fallback goes here
  }
}

, , , Underscore. .

+7

, Lodash, Lodash, Underscore:

(function () {
    if (_.VERSION) {
    console.log('underscore loaded');
  }
})();

https://jsfiddle.net/2x0g8xyt/

+2

All Articles