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.
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.
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");
});
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