Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I install underscore.js?

I am trying to install underscore.js so I can use it in my browser, but it seems all installation instructions are meant for servers. How do I use this in my web browser? I know JS has no import or require so I am not sure what to do. Thanks

like image 863
chopper draw lion4 Avatar asked Jun 15 '14 18:06

chopper draw lion4


3 Answers

  • Open some webpage in Google chrome or Mozilla Firefox. For example, google.com.
  • And then press F12 key.
  • Select Console Tab.And the type or Copy-paste the following code:

var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js'; document.head.appendChild(script);

and press Enter.

Then start typing your underscore js commands on the console.

like image 68
Gil Baggio Avatar answered Sep 22 '22 23:09

Gil Baggio


You don't install a JavaScript library in order to use it - you need to include it. If you have dependencies, then only the order (for example first underscore.js and then your custom library that uses underscore.js) is important. One possibility would be to use some Content Delivery Network (CDN), so you don't need to download the library locally. Common CDN's are:

  • Google CDN
  • Microsoft CDN
  • cdnjs.com

If you download the library and host it on your server, than just put it in your project directory (or in a directory called scripts).

The code that includes the underscore.js library used from a custom library could look like this:

JS library demo.js

// function using underscore.js
function demo() {
    var input = [1, 2, 3];
    var output = _.map(input, function(item) {
            return item * 2;
    });
    alert(input + " - " + output);
}

and then in a second file demo.html:

<!DOCTYPE HTML>
<html>
    <head>
        <!-- first include the underscore.js library -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js" type="text/javascript"></script>
        <!-- or if the file is downloaded locally -->
        <!-- <script src="scripts/underscore.js" type="text/javascript"></script>-->
        <!-- then the custom JS library -->
        <script src="demo.js" type="text/javascript"></script>
    </head>
    <body>
        <!-- call the custom library function -->
        <a href="#" onclick="demo();">Start the script using underscore.js</a>
    </body>
</html>

The output is as expected:

1,2,3 - 2,4,6
like image 36
keenthinker Avatar answered Sep 20 '22 23:09

keenthinker


Just paste following code into head section of your .html file.

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3  /underscore-min.js">
</script>
like image 33
Nelliusz Frącek Avatar answered Sep 19 '22 23:09

Nelliusz Frącek