Javascript modules, passing jQuery when it may not be loaded -


i'm learning module pattern javascript in order tidy code , reduce need long 'global' javascript file. consequence of this, have top level 'namespace' module, , utility module in same file. utility module has functions require jquery, , others not.

on lightweight pages use no jquery, don't want load library (i have reason not doing so). problem arises when jquery passed parameter module in following:

module.vars = (function (variables,$) {    variables.cdn = undefined; //global clientside cdn    variables.version = undefined; //global clientside cdn version    variables.istouchscreen = undefined; //global touchscreen status     //check if jquery exists, if patch jquery dependent functions    if ($) {        $(document).ready(function () {            variables.istouchscreen = $('html').is('.touch');        });    }     return variables;  }(module.vars || {}, jquery)); 

the code stops on pages don't load jquery, stating jquery undefined - fair enough. if change last line to:

}(module.vars || {}, jquery || false)); 

the code still complains jquery undefined. thought, perhaps erroneously, if jquery undefined, passed undefined in instance , instead take value false (which logic dictates wouldn't necessary anyway).

how around problem when jquery may or may not present? attempted put following @ top of script:

var jquery = jquery || false; 

thinking take value of jquery if loaded. works in modern browsers this, ie8 complains gets set false if jquery being loaded first on page.

the scripts loaded in correct order in html, jquery first, module afterwards.

when checking cause, ie8 returns $ object , jquery false. if not set above line in script, jquery returns same object $.

sadly have cater ie8 well, how around issue of optional presence of jquery?

edit: snippet of module , there other functions depend on jquery, won't implemented if jquery not available

i seem have found answer works after worked out how implement elanclrs suggestion - put following @ top of modules:

var jq = jq || false;    if (typeof jquery !== 'undefined') {    jq = jquery; } 

then in module, pass jq instead of jquery.

the reasoning behind answer pointed @ in question: error when passing undefined variable function?


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -