bobsilon
bobsilon

Reputation: 1668

Javascript Files Priority on document.ready()

Is it important to call JavaScript files in the order that they are needed when we use document ready for inline script functions?

For example, imagine I want to call jQuery's counter-up plugin under jQuery Waypoints. It's required to load jQuery, Waypoints and finally the counter-up script respectively in the header of the document and to call counterup() in an inline script as below:

    <script>
        $('.counter').counterUp({
            delay: 10,
            time: 1000
        });
    </script>

What happens if I call that function under $(document).ready and move script import statements to the bottom of <body>?

Is it needed to call the required files at the bottom of body respectively? (eg. import jquery.min.js at the end of all other libraries.)

Upvotes: 0

Views: 2434

Answers (1)

laruiss
laruiss

Reputation: 3816

$ Will throw a Reference Error if jQuery is not defined before (i.e. if jquery.min.js is not imported before $ is evaluated).

So you have to first add a <script> tag with jquery before the <script> with your custom code, which should be, by the way, in a seperate file.

Then, since <script> can modify the DOM, the "DOM ready" event will not be fired until all the JS files are downloaded and evaluated and executed, even if you put them outside of the <html> tag.

That being said, if (and only if) your code with the plugins are all inside the "domready" callback, you can add your script tag with the plugins after your custom code, like this :

<!DOCTYPE html>
<html>
<head>
  <title>JS Bin</title>
  <meta charset="utf-8">


  <link rel="stylesheet" href="//cdn.jsdelivr.net/jquery.tooltipster/2.1.4/css/tooltipster.css">
</head>
<body>
  <div id="test" title="Beautiful tooltip plugin!">Hello world!</div>
</body>
  </html>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <script>
    jQuery(function($) {
      $("#test").tooltipster();
      console.log('Test OK');
    });

  </script>
  <script src="//cdn.jsdelivr.net/jquery.tooltipster/2.1.4/js/jquery.tooltipster.min.js"></script>

See jsbin

Upvotes: 1

Related Questions