Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript modules, passing jQuery when it may not be loaded
    text
    copied!<p>I'm learning the module pattern for javascript in order to tidy up my code and reduce the need for a long 'global' javascript file. As a consequence of this, I have a top level 'namespace' module, and a utility module in the same file. The utility module has some functions that require jquery, and others that do not.</p> <p>On lightweight pages that use no jQuery, I don't want to load the library (I have a very good reason for not doing so). The problem arises when jQuery is passed as a parameter to the module as in the following:</p> <pre><code>MODULE.vars = (function (variables,$) { variables.cdn = undefined; //global for clientside cdn variables.version = undefined; //global for clientside cdn version variables.isTouchScreen = undefined; //global for touchscreen status //Check if jquery exists, if so patch the jquery dependent functions if ($) { $(document).ready(function () { variables.isTouchScreen = $('html').is('.touch'); }); } return variables; }(MODULE.vars || {}, jQuery)); </code></pre> <p>The code stops on pages that I don't load jquery, stating that jQuery is undefined - fair enough. If I change the last line to:</p> <pre><code>}(MODULE.vars || {}, jQuery || false)); </code></pre> <p>the code still complains that jQuery is undefined. I thought, perhaps erroneously, that if jQuery was undefined, it would be passed as undefined in this instance and instead take up the value false (which logic dictates wouldn't be necessary anyway).</p> <p>How do I get around this problem when jQuery may or may not be present? I attempted to put the following at the top of the script:</p> <pre><code>var jQuery = jQuery || false; </code></pre> <p>thinking that this would then take up the value of jQuery if it was loaded. It works in modern browsers with this, but IE8 complains as it gets set to false even if jQuery is being loaded first on a page.</p> <p>The scripts are all loaded in the correct order in the html, jQuery first, then my module afterwards.</p> <p>When checking for the cause, IE8 returns $ as an object and jQuery as false. If i do not set the above line in the script, jQuery returns as the same object as $.</p> <p>Sadly I <em>have</em> to cater for IE8 as well, so how do I get around this issue of the optional presence of jQuery?</p> <p>Edit: This is only a snippet of the module and there are other functions that depend on jquery, but simply won't get implemented if jquery is not available</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload