Skip to content

Instantly share code, notes, and snippets.

@tedw
Last active June 26, 2018 14:13
Show Gist options
  • Save tedw/97c0a847721baef835ee9c33ee2bc401 to your computer and use it in GitHub Desktop.
Save tedw/97c0a847721baef835ee9c33ee2bc401 to your computer and use it in GitHub Desktop.
Prevent errors when jQuery code is run on a site without jQuery
/* This can be helpful in development when testing a site’s GTM container if it runs custom jQuery code */
// Overwrite jQuery function with dummy that returns itself
window.jQuery = function() {
console.warn(
"Something attempted to call jQuery but it’s not used this page"
);
return jQuery; // enables chaining
};
// Most common jQuery methods (not exhaustive, add anything else you need)
var methods = [
"addClass",
"after",
"append",
"attr",
"before",
"click",
"css",
"data",
"each"
"hide",
"html",
"off",
"on",
"prepend",
"removeClass",
"show",
"text",
"toggle",
"toggleClass",
"val",
];
// Add the above methods to our dummy jQuery function (using ES5 so this code can be inlined without a build step)
for (var i = 0, len = methods.length; i < len; i++) {
window.jQuery[methods[i]] = function() {
return false;
};
}
// Make dummy Event function
window.jQuery.Event = function() {
return {};
};
// Create alias
window.$ = window.jQuery;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment