Due to Wordpress loading jQuery in nonconflict-mode, I must wrap my scripts inside jQuery(function($){...})
The parent script executes as expected. However, I conditionally load a 2nd script via getScript:
$.getScript('js/2nd.js').done(function() {
editElem();
});
Do I also need to wrap everything inside "2nd.js"? If I don't do it, nothing happens - not even an error is thrown in Chromes console. If I wrap it, it says "editElem is not defined" - although my "2nd.js" of course defines it.
Thanks for your insights.
It is best to still wrap it — the goal of noconflict mode is to keep your code working even if the $
variable is taken by another library. As you've discovered, though, your global functions are no longer global once they're inside a closure!
Globals are not considered JavaScript's finest achievement, and this case is a good example; module loaders like RequireJS (which can perhaps be extended for lazy loading?) can make life easier down the road.
That said, if you only have two files and just want to export your functions from 2nd.js
, you can do that without any extra libraries:
(function ($) {
// ... define your functions
function editElem () {
}
function otherFunc () {
}
function privateFunc () {
}
// export any functions needed by scripts outside this file.
window.LazyUtils = {
editElem: editElem,
otherFunc: otherFunc
};
}( jQuery ));
After that you should be able to call LazyUtils.editElem()
from your first JS file, the console, or wherever. Up to you what to name that module - "LazyUtils" is just an example.