InfoHeap
Tech
Navigation
  • Home
  • Tutorials
    • CSS tutorials & examples
    • CSS properties
    • Javascript cookbook
    • Linux/Unix Command Line
    • Mac
    • PHP
      • PHP functions online
      • PHP regex
    • WordPress
  • Online Tools
    • Text utilities
    • Online Lint Tools
search

Javascript

    Javascript strings

    • Javascript - check if string is number
    • Javascript - parseInt
    • string ends with check
    • string starts with check

    Javascript Array

    • array forEach
    • array append item
    • array remove last item
    • array prepend item
    • array remove first item
    • create array from 0 to N-1
    • convert array to json string

    Javascript control flow

    • for-in loop to iterate over keys of javascript object

    Javascript DOM

    • Javascript - DOM appendChild example
    • Javascript - get computed style of an element
    • Javascript - how to view text inside DOM element
    • Javascript - img onload examples
    • Javascript - ready vs on load event handler example
    • Javascript - use querySelector to set dom element html
    • Javascript DOMContentLoaded listener example
    • Javascript event bubble vs capture
    • Javascript how to stop event propagation
    • Javascript onscroll event handler
    • Javascript onscroll event handler with throttling
    • Make an element draggable using Vanilla Javascript
    • Multiple onload handlers using vanilla Javascipt
    • Use universal selector to get all DOM nodes in vanilla Javascript
    • document querySelector examples
    • dump all handlers on window object

    Javascript Cookbook

    • Are Javascript functions objects?
    • Declare and invoke anonymous function
    • HTML5 drag and drop
    • JSLint on command line on Ubuntu
    • Javascript - call vs apply
    • Javascript - implement class using function
    • Javascript - iterate over function arguments
    • Javascript - print all methods of an object
    • Javascript - run a function at regular interval
    • Javascript - textarea and text input select all
    • Javascript arrow function examples
    • Javascript check if variable is defined
    • Javascript local and global variables
    • Javascript parse json string
    • Javascript prototype examples
    • Javascript settimeout example
    • Javascript sleep implementation
    • Requirejs - quickstart guide for beginners
    • catch errors using window.onerror
    • print javascript object to log

    Javascript libraries

    • AngularJS
    • CasperJS
    • PhantomJS
    • React
    • jQuery

    Javascript global functions

    • Javascript - Number function
     
    • Home
    • > Tutorials
    • > Javascript

    Requirejs – quickstart guide for beginners

    By admin | Last updated on Mar 20, 2016

    RequireJS is a JavaScript file and module loader. It can be used in browsers and other javascript environments like Node. This article is intended as a quickstart guide for requirejs for beginners with some comments on when it can be used.

    requirejs

    Requirejs example

    Here is a simple example using requirejs:

    <!DOCTYPE html>
    <html>
    <head>
    <title>RequireJS basic example</title>
    <script src="/demo2/requirejs-example/require.js"></script>
    <script>
    requirejs.config({
        //By default load any module from here
        baseUrl: '/demo2/requirejs-example'
    });
    </script>
    </head>
    
    <body>
    <h1>RequireJS basic example</h1>
    <div id="data1"></div>
    <script type="text/javascript">
      require(["foo"], function (foo) {
        document.getElementById("data1").innerHTML = "foo.key1=" + foo['key1'];
        console.log("foo=%o", foo);
      });
    </script>
    </body>
    </html>
    refresh done
    try it online

    Here is the foo.js code used in above example:

    define({
        key1: "val1",
        key2: "val2"
    });
    

    Few points to note:

    1. Requirejs needs modules to be declared using define.
    2. define is a function defined in require.js source.
    3. Require is used to load additional modules.
    4. Both define and require can specify dependencies.

    Requirejs base directory

    The base-dir can be set in three ways in requirejs:

    1. Implicitly set to current directory of the page is nothing is specified.
    2. If data-main attribute is specified as shown below, then the directory of main js becomes base-dir.
      <script data-main="js/app.js" src="js/require.js"></script>
      
    3. Using requirejs.config (our example used this) as shown below:
      requirejs.config({
          //By default load any module IDs from js/lib
          baseUrl: 'js/lib'
      });
      

    Requirejs – using shim for “browser globals” scripts

    Require can also be to configure the dependencies and exports for traditional “browser globals” scripts that do not use define() to declare the dependencies and set a module value. Here is an example:

    requirejs.config({
      shim: {
        'bar' : {
          // These script dependencies should be loaded before loading bar.js
          // deps: ['dep1', 'dep2'],
          // Once loaded, use the global 'Bar' as the module value.
          exports: 'Bar'
        }
      }
    })
    
     Once this is done, regular require call can be used for javascript file bar.js as shown below:
    require(["bar"], function(Bar) {
     // do something...
    });
    
    Here is sample bar.js code
    var Bar = function () {
      this.key3 = "val3";
      this.key4 = "val4";
    };
    

    Requirejs – additional comments

    1. For detailed official documentation visit requirejs site.
    2. Requirejs seems more suitable when project is big and there are too many dependencies.
    3. It is also handy util for loading multiple scripts and doing a callback once all the scripts are loaded.
    4. For simple projects requirejs does not seem to be that useful.
    5. Requirejs needs each module to be in its own file. But in production you may want to combine multiple javascript files. You may want to look at requirejs optimization to achieve this.

    Suggested posts:

    1. node – how to find version of installed package
    2. CSS general sibling selector
    3. HTML import
    4. jQuery – find total number of DOM elements
    5. Embed youtube video with javascript on-click lazy loading approach
    6. Javascript prototype examples
    7. jQuery – get javascript object
    8. How to display auto fade out message using jQuery
    Share this article: share on facebook share on linkedin tweet this submit to reddit
    Posted in Tutorials | Tagged Javascript, Javascript cookbook, Tutorials, Web Development
    • Browse content
    • Article Topics
    • Article archives
    • Contact Us
    Popular Topics: Android Development | AngularJS | Apache | AWS and EC2 | Bash shell scripting | Chrome developer tools | Company results | CSS | CSS cookbook | CSS properties | CSS Pseudo Classes | CSS selectors | CSS3 | CSS3 flexbox | Devops | Git | HTML | HTML5 | Java | Javascript | Javascript cookbook | Javascript DOM | jQuery | Kubernetes | Linux | Linux/Unix Command Line | Mac | Mac Command Line | Mysql | Networking | Node.js | Online Tools | PHP | PHP cookbook | PHP Regex | Python | Python array | Python cookbook | SEO | Site Performance | SSH | Ubuntu Linux | Web Development | Webmaster | Wordpress | Wordpress customization | Wordpress How To | Wordpress Mysql Queries | InfoHeap Money

    Copyright © 2025 InfoHeap.

    Powered by WordPress