- RequireJS Tutorial
- RequireJS - Home
- RequireJS - Overview
- RequireJS - Environment Setup
- RequireJS - Configuration
- RequireJS - AMD Modules
- RequireJS - Defining Function
- RequireJS - Optimizer
- RequireJS - jQuery
- RequireJS - NodeJS
- RequireJS - Dojo
- RequireJS - CommonJS
- RequireJS - Plugins
- RequireJS Useful Resources
- RequireJS - Quick Guide
- RequireJS - Useful Resources
- RequireJS - Discussion
RequireJS - Loading jQuery from CDN
jQuery uses CDN (Content Delivery Network) to define the dependencies for jQuery plugins by calling the define() function.
Loading jQuery
define(["jquery", "jquery.load_js1", "jquery.load_js2"], function($) { $(function() { //code here }); });
Example
The following example uses CDN to define the dependencies for jQuery plugins. Create a html file with the name index.html and place the following code in it −
<!DOCTYPE html> <html> <head> <title>Load jQuery from a CDN</title> <script data-main = "app" src = "lib/require.js"></script> </head> <body> <h2>Load jQuery from a CDN</h2> <p>Welcome to Tutorialspoint!!!</p> </body> </html>
Create a js file with the name app.js and add the following code in it −
// you can configure loading modules from the lib directory requirejs.config ({ "baseUrl": "lib", "paths": { "app": "../app", //loading jquery from CDN "jquery": "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min" } }); //to start the application, load the main module from app folder requirejs(["app/main"]);
Create a folder called app and load the main.js module from this folder −
define(["jquery", "jquery.load_js1", "jquery.load_js2"], function($) { //loading the jquery.load_js1.js and jquery.load_js2.js plugins $(function() { $('body').load_js1().load_js2(); }); });
Create one more folder called lib to store the require.js file and other js files as shown below −
lib/jquery.load_js1.js
define(["jquery"], function($) { $.fn.load_js1 = function() { return this.append('<p>Loading from first js file!</p>'); }; });
lib/jquery.load_js2.js
define(["jquery"], function($) { $.fn.load_js2 = function() { return this.append('<p>Loading from second js file!</p>'); }; });
Output
Open the HTML file in a browser; you will receive the following output −
requirejs_jquery.htm
Advertisements