jQuery by Patrik

Making sure that the jQuery library is loaded

How can we ensure that the jQuery library is loaded before any of our JavaScript codes uses $ or jQuery variable?

In order to do so, we can test whether window.jQuery is defined before referencing the $ or jQuery variable. If window.jQuery is not defined yet, then we wait for some time before checking again.

<body>
    <script async src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script>
        function run() {
            if (window.jQuery) {
                $(document).ready(function() {
                    alert('Hello there');
                });
            }
            else {
                setTimeout(run, 50);
            }
        }
        run();
    </script>
</body>

Further explanation can be found at How to prevent "Uncaught ReferenceError: jQuery / $ is not defined" - Techcoil Blog

jQuery

Comments

Leave a Comment

All fields are required. Your email address will not be published.