I am using require JS and want to know the best method to use a CDN version of jQuery. I hear the 1.7 version is "AMD" which is supposed to help but can't find a straight example. Hope some RequireJS gurus can help me out.
Officially there are two ways of using jQuery: CDN Based Version - You can include jQuery library into your HTML code directly from Content Delivery Network (CDN). Local Installation - You can download jQuery library on your local machine and include it in your HTML code.
jQuery CDN is a light JavaScript framework that speeds up website development by simplifying event handling, animation, AJAX interactions, and HTML page traversal. The jQuery UI CDN makes HTML client-side scripting easier, making developing Web 2.0 applications easier.
The best-performing CDN depends a bit on your needs. If you don't need HTTPS support, the fastest CDN is actually the official jQuery CDN, provided by Media Temple. Google's Libraries API CDN is a good second choice after that. If you need support for HTTPS, your best option is Google's Libraries API CDN.
Step 1: Open the HTML file in which you want to add your jQuery with the help of CDN. Step 2: Add <script> tag between the head tag and the title tag which will specify the src attribute for adding your jQuery. Step 3: After that, you have to add the following path in the src attribute of the script tag.
jQuery 1.7 registers itself as an AMD module by the name of 'jquery', so you need to create a mapping for 'jquery' using the paths config:
requirejs.config({ paths: { 'jquery' : 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min' } }); require(['jquery'], function($) { //$ points to jQuery });
Note however that RequireJS loads modules asynchronously and out of order, so if you have jQuery plugins you want to use that are not wrapped in define(['jquery'], function ($){ /* plugin code goes here */ });
calls, the plugin could execute before jQuery is loaded.
See the require-jquery project's README on ways to deal with files that depend on jQuery but do not wrap themselves in define()
calls.
@jrburke's answer does not work for me. According to the RequireJS api doc, you should not include the file extension in the path. So here is the working code:
requirejs.config({ paths: { 'jquery': 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min' } }); require(['jquery'], function($) { //$ points to jQuery });
I have a working example on jsfiddle: http://jsfiddle.net/murrayju/FdKTn/
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