:::: MENU ::::

RequireJS example – loading desktop vs mobile javascript libraries and overriding functions

requirejs

RequireJS is a javascript library that is used to load other javascript files in certain orders based upon its dependency. However it can be also used for writing modular javascript other than modular design pattern. I won’t cover basics of RequiteJS here. If you are new to RequireJS, you could read this sitepoint post first.

javascript_obj_override

JavaScript Object based Modular Code

Let’s say we have core library called core.js contains all base library functions.

Now let’s create mobile specific module that uses above core.js and extends its function for its use.

Above mobile module mobileLib will use its own property and render function and override on Core modules. However, other core’s functions (i.e. util()) will be available to it.

Extending core library with jQuery extend() function

So this.util() within mobileLib will set screenwidth = “320px” and call Core library’s util() function.

Demo


Let’s create library for desktop users.

Extending core library

So this.util() within mobileLib will set screenwidth = “600px” and call Core library’s util() function.

Demo

Handling these modules with RequireJs

So, we have 4 files

Exporting functions from core.js

Using core.js within mobile.js using require.js

Using core.js within desktop.js using require.js

Initializing this scripts

In mobile webpages (or cms template) just drop this line for desktop.

In desktop pages add this script

Check Demo or Download Code

Share and Enjoy

  • DZone
  • Google Plus
  • LinkedIn
  • Twitter
  • Facebook
  • Email

So, what do you think ?

  •