Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sourcing jQuery from a CDN?

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.

like image 633
wilsonpage Avatar asked Nov 09 '11 20:11

wilsonpage


People also ask

Can jQuery be accessed via CDN?

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.

What is the CDN for jQuery?

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.

What is the best CDN for jQuery?

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.

How link jQuery CDN to HTML?

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.


2 Answers

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.

like image 75
jrburke Avatar answered Sep 21 '22 17:09

jrburke


@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/

like image 36
murrayju Avatar answered Sep 19 '22 17:09

murrayju