0
votes

Wordpress loads jQuery automatically. I want to use it, but I get:

jQuery is not defined

This is because various plugins mess with the ordering of scripts. So there's no guarantee that my script will load AFTER jQuery is loaded. So if it loads before, I get that error.

Can I wrap my script in something that waits for jQuery to load, and then executes my script?

Notes

  • I don't want to manually load jQuery, because then I'll break various plugins... I must let Wordpress load it as usual
  • I'm not a PHP person, so I don't want to hack the theme... I just want to wrap my script in a cross-browser "jquery waiting script"
3
@Adder Thanks. But that talks about using defer, which I cannot control as Wordpress controls jquery, and about document ready which is not relevant because jquery is not yet loaded.lonix

3 Answers

2
votes

All functions in window.deferAfterjQueryLoaded will be runned after jQuery is defined, so if you push all your inizializations in window.deferAfterjQueryLoaded you can be sure that they will be runned after jQuery

<script>
    if (!window.deferAfterjQueryLoaded) {
        window.deferAfterjQueryLoaded = [];

        //delete Object.defineProperty; //add this if you want to check the support
        if (typeof (Object.defineProperty) === "function") {
            Object.defineProperty(window, "jQuery", {
                set: function (value) {
                    window.setTimeout(function () {
                        $.each(window.deferAfterjQueryLoaded, function (index, fn) {
                            fn();
                        });
                    }, 0);
                    Object.defineProperty(window, "jQuery", {value: value});
                },

                configurable: true
            });
        } else {
            nIntervId = window.setInterval(function () {
                if (typeof (jQuery) !== "undefined") {
                    $.each(window.deferAfterjQueryLoaded, function (index, fn) {
                        fn();
                    });
                    clearInterval(nIntervId);
                }
            }, 10);
        }
    }
    window.deferAfterjQueryLoaded.push(function () {
        (function ($) {
            console.log("After jquery is loaded");
        })(jQuery);
    });

</script>
<script>
    window.deferAfterjQueryLoaded.push(function () {
        (function ($) {
            console.log("After jquery is do something else");
        })(jQuery);
    });
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

You can read more abount Object.defineProperty, you can check the cross browser support here

1
votes

IMHO when 'load' is triggered you can use jQuery:

window.addEventListener('load', (event) => {
  // your code
});
0
votes

Maybe this helps:

$j = jQuery.noConflict();

Then use $j

Tom