How to use jQuery in global imported functions without jQuery.ready

170 views Asked by At

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!

1

There are 1 answers

0
Quentin On

A copy of jQuery is assigned to $ by default.

It will only be undefined if you:

… so don't do any of those.