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
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.
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:
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With