'How to use jQuery in global imported functions without jQuery.ready
my code in JS is getting very large right now and so I wanted to outsource sections to other files, for clarity.
In my main file I use
jQuery(document).ready(function ($) {
$.getScript("/wp-content/plugins/file2.js",function(){
console.log("loaded 2");
});
$.getScript("/wp-content/plugins/file3.js",function(){
console.log("loaded 3");
});
This works. In file 2 and 3 I use jQuery with functions like:
function getData(){
$.("#foo").on("click", function(){});
}
So I am getting the error
$ is undefined
because I do not declare $. But if I wrap around the $.ready function I can't access the functions inside file 2 which are used by the other files.
How can I 'declare' the $ separately without loosing the global scope of the function. Or is there even a better way? I only include in html:
<script src="/wp-content/plugins/file1.js" type="text/javascript"></script>
Thanks for helping!
Solution 1:[1]
A copy of jQuery is assigned to $ by default.
It will only be undefined if you:
- Overwrite it
- Mask it
- Call
$.noConflict()
… so don't do any of those.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin |
