Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery loaded async and ready function not working

In order to optimize the load of my document, I use to load jQuery async like that

<script async type="text/javascript" src="js/jquery-1.12.3.min.js"></script>

Then I call a script using jQuery :

<script type="text/javascript">
    jQuery(document).ready(function() {
    App.init();
    OwlCarousel.initOwlCarousel();
    FancyBox.initFancybox();
    StyleSwitcher.initStyleSwitcher();
    
    });
</script>

It returns me that jquery is not defined.

I don't know what should I use, I though that .readyfunction would wait until all document is loaded before calling it.

The same for Bootstrap library, It tells me that jQuery is not defined.

I've tried to ask the script to be loaded at the end, but it still does not work properly.

like image 492
Stanislas Piotrowski Avatar asked Dec 02 '22 14:12

Stanislas Piotrowski


2 Answers

Since jquery script is loaded asynchronously, jquery is not loaded on the moment your script is executing. So you need to wait for it to load by subscribing on load event like this:

<script async id="jquery" type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>

Then listen for a load event on this element

<script type="text/javascript">
  document.getElementById('jquery').addEventListener('load', function () {
    App.init();
    OwlCarousel.initOwlCarousel();
    FancyBox.initFancybox();
    StyleSwitcher.initStyleSwitcher();
  });
</script>

But I don't know why someone wants to do things like this.

To optimize page loading speed it is better to put all you javascript at the end of the body, so content will be loaded first, and scripts won't delay page rendering event if it's synchronously loaded.

Edit: I agree with comment and consider previous paragraph not the best way of loading jQuery to the page

like image 134
Andrey Avatar answered Dec 24 '22 23:12

Andrey


Question Script Tag - async & defer has good answer to your problem.

In a nutshell you cannot load jQuery, or other library, asyncronously when some other script depends on it without some additional asyncronous handling for executing the scripts depending on the library.

like image 34
ighea Avatar answered Dec 24 '22 23:12

ighea