Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript requiring libraries

I'm quite new to the world of JavaScript (specially when it comes to libraries). Quite a few of them tell you to use require('libName') as a way to integrate the library on your web page/application. Could someone explain to me how exactly that works and how to implement this? Cause by default require() doesn't work.

like image 861
Adonis K. Kakoulidis Avatar asked Jan 15 '23 03:01

Adonis K. Kakoulidis


2 Answers

JavaScript in the browser doesn't have a require function, this functionality is provided by external libraries following the two most popular specs: CommonJS and AMD. Take a look at RequireJS that plays nice with both patterns.

JavaScript on the server (NodeJS), uses CommonJS spec by default.

like image 182
elclanrs Avatar answered Jan 16 '23 21:01

elclanrs


Here is a very lightweight require:

var require = function(src, success, failure){
    !function(source, success_cb, failure_cb){
            var script = document.createElement('script');
            script.async = true; script.type = 'text/javascript'; script.src = source;
            script.onload = success_cb || function(e){};
            script.onerror = failure_cb || function(e){};
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);
    }(src, success, failure);
}

require('js/jquery.js', function(){
    console.log('jQuery is ready to use');
}, function(){
    console.log("Something went wrong loading this script");
});
like image 38
Rob M. Avatar answered Jan 16 '23 21:01

Rob M.