5

I've got some jQuery code that requires 2 external .js to complete loading before I can successfully do what I need to do, and $(document).ready isn't working consistently enough; sometimes it works, other times it gets overwritten by the external .js code.

Is there some way to ensure that the page is completely done loading, including all external .js before my jQuery executes?

J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
  • How are the 2 external js files included in the page? Are they script tags in the head, or are they loaded with some other script method? – Reinstate Monica Cellio Nov 01 '13 at 16:07
  • This is a WordPress site, they get loaded via a WordPress function, and the external .js code that I'm altering is from a plugin. I write my own jQuery code in a custom.js in my theme, called from the theme's functions.php. – J. Scott Elblein Nov 02 '13 at 16:20

2 Answers2

9

$(document).ready only waits for the DOM to be loaded. To wait until all resources in the page (including images, objects, scripts...) have been (down)loaded you can use window.onload:

window.onload = function () {
  // do stuff
};

Additionally you should read: window.onload vs $(document).ready()

Community
  • 1
  • 1
Sébastien
  • 11,860
  • 11
  • 58
  • 78
  • 1
    If any of his external js uses `window.onload` it's likely his problem will continue to persist (not likely, but still probable). To be safe, I'd avoid using `window.onload` for this use case. – John Nov 01 '13 at 16:57
3

It's impossible know what's a better way when we don't know anything about your project but, in general, it's good practice to do all your script loading right before the closing </body> tag. Then make sure you're jquery code is loaded after it's dependencies are.

<!DOCTYPE html>
<html lang="en">
  <head>
      <!-- your head stuff -->
  </head>
  <body>

    <!-- your page markup here -->

    <!-- load scripts here -->
    <script src="library_with_no_dependencies.js"></script>
    <script src="jquery.js"></script>
    <script src="library_with_dependency_on_jquery.js"></script>
    <script src="your_js_code.js"></script>

    <script>
      // or you could embed your js here
    </script>

  </body>
</html>

Just list them in the same order that you want them to load in. Using this method you don't need to use jquery's $(document).ready or window.onload, and your code will be executed much sooner than using either of those methods.

You don't want to wait for everything to load, just the libraries that your javascript code is dependent on.

John
  • 3,866
  • 6
  • 33
  • 37