jQuery noConflict

If you need to inject a specific version of jQuery into a webpage that may or may not already have a different version of jQuery, or if you specifically need two different versions loaded, then you can use jQuery.noConflict.

You might use this if you’re building a custom control that gets injected into a page, where you want to make sure your stuff works as intended, but you don’t want to accidentally upgrade or downgrade the main page’s jQuery.

Sample Code

This sample will show how to load jQuery 1.8.3 into a page which may or may not already have a different version loaded.

var _jq183;

function load183() {
    if (typeof window.jQuery === "function" && window.jQuery.fn && window.jQuery.fn.jquery === "1.8.3") {
        _jq183 = window.jQuery;
        return;
    }

    if (typeof window.jQuery === 'undefined' || !window.jQuery.fn || (window.jQuery.fn.jquery !== "1.8.3")) {

        var done = false;

        var body = document.getElementsByTagName("body")[0];
        var scr = document.createElement("script");
        scr.setAttribute("src", "https://code.jquery.com/jquery-1.8.3.min.js");
        scr.onload = scr.onreadystatechange = function () {
            if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
                done = true;
                _jq183 = jQuery.noConflict(true);
                scr.onload = scr.onreadystatechange = null;
                body.removeChild(scr);
            };
        };
        body.appendChild(scr);
    };
}

function showVersion() {
    if (typeof $ === "undefined") {
        console.log("$ is undefined");
    } else {
        console.log("$: " + $.fn.jquery);
    }
    if (typeof jQuery === "undefined") {
        console.log("jQuery is undefined");
    } else {
        console.log("jQuery: " + jQuery.fn.jquery);
    }
    console.log("_jq183: " + (_jq183 ? _jq183.fn.jquery : "N/A"));
}

You may get an error message, like:

Refused to load the script 'https://code.jquery.com/jquery-1.8.3.min.js' because it violates the following Content Security Policy directive: "script-src somethingsomething.com".</code>

From what I’ve read, if you get this, you’re out of luck because the site won’t allow you to inject a script from another domain.

jQuery Filter by Data

jQuery won’t let you search using a regular selector for data attributes if those data attributes were added using the data function:

jQuery("#something").data("somekey", "someval");
jQuery("#something[data-somekey=someval]"); // does not find it

Instead, define a new function:

jQuery.fn.filterByData = function(prop, val) {
    return this.filter(function() { 
        return jQuery(this).data(prop) == val;
    });
};

jQuery("#something").filterByData("somekey", "someval"); // finds it

StackOverflow question: http://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value

Stackoverflow answer: http://stackoverflow.com/a/15651670/111266

jQuery AJAX

I’m sure there’s a perfectly good explanation for why the “always” function has two different signatures – one for requests that were successful and a different one for unsuccessful ones. But whatever their reason, they’re wrong. This is just plain stupid that you don’t know what kind of object the first and third parameters are. But they never asked me before they implemented it, so there’s nothing I can do about it…

var jqXHR = jQuery.ajax(ajaxParams);
jqXHR.done(function(data, textStatus, jqXHR) {});
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown ) { });
The ajaxParams object contains lots of different options - the ones I generally use are as follows:
{
    // absolute or relative
    url: "/path/to/some/url",

    // will you be receiving "json", "html", "text", or "xml" back
    // 99% of the time I use json or html. If json, then the result will already
    // be parsed into a javascript object.
    dataType: "json",

    // what kind of data you are posting
    // 'application/x-www-form-urlencoded; charset=UTF-8' is the default
    contentType: "application/json; charset=utf-8",

    // This one is fun. If you're posting form-urlencoded, then this can 
    // either be a string representing the form post, like name=John&age=34
    // or it can be a javascript object and jQuery will automatically build
    // the string: { name: "John", age: 34 }
    // However, if you are posting JSON, then it needs to be a JSON string (not
    // an object, but the JSON representation of that object):
    // JSON.stringify({ name: "John", age: 34 })
    data: myData
}

There’s a lot more you can do with it – see the documentation.