If JQuery does exist in scope will these behave in the same way?
The $ is used to constrain the scope to inside each function I guess, I'm not exactly sure why however. The second snippet is the original code, I'm attempting to add a check for jquery before it's called as in the first snippet.
First:
(function () {
if (!window.jQuery) {
alert('Error: JQuery not loaded.');
return;
}
main(jQuery);
})();
function main($, undefined) {
alert("main 1");
//do some work on $
}
Second:
(function ($) {
if (!$) {
alert('Error: JQuery not loaded.');
return;
}
alert("main 2");
//do some work on $
})(jQuery);
Third (Maybe this is slightly better?):
(function () {
if (!window.jQuery) {
alert('Error: JQuery not loaded.');
return;
}
var main = function ($, undefined) {
alert("main 3");
//do some work on $
}
main(jQuery);
})();
This is the best solution for me.
(function () {
if (!window.jQuery) {
alert('Error: JQuery not loaded.');
return;
}
var main = function ($, undefined) {
alert("main 3");
//do some work on $
}
main(jQuery);
})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.