1

I am declaring global variables across different js files, which are then used in different files. I need to make sure that all js have loaded before I start execution. I am also trying to move to modular js using require.js. But for now I need a quick solution. Is it safe to run my js code under $().ready()? I guess script tags would be loaded synchronously and thus DOM wont be ready until all scripts have been loaded.

Or does $(window).load() guarantee that all script files have been loaded.

Thanks!

Amit
  • 15,217
  • 8
  • 46
  • 68
shreyj
  • 1,759
  • 3
  • 22
  • 31
  • 1
    possible duplicate of [jQuery - What are differences between $(document).ready and $(window).load?](http://stackoverflow.com/questions/8396407/jquery-what-are-differences-between-document-ready-and-window-load) – Ram Jan 16 '14 at 09:57
  • `window.load` is the answer. you can also read http://stackoverflow.com/questions/4584373/difference-between-window-loadfunction-and-document-readyfunction – STEEL Jan 16 '14 at 09:57
  • This is a similar question/answer: http://stackoverflow.com/questions/6195257/does-ready-fire-before-or-after-all-inline-scripts-have-been-loaded?rq=1 – John Jan 16 '14 at 09:58
  • What I am asking is - is DOM ready before js files are loaded or not. Images are loaded async therefore ready event would be trigerred before images load. But I think js in script tags are loaded synchronously. SO DOM can't be ready until js are loaded ? – shreyj Jan 16 '14 at 10:03
  • "What I am asking is - is DOM ready before js files are loaded or not" Check duplicates, all is explained – A. Wolff Jan 16 '14 at 10:05

2 Answers2

5

If you load your scripts inline, the DOM will not be ready until those scripts are loaded, and therefore the $().ready() function will not fire until these resources are loaded. If you use the async tag in the script elements then the DOM may be classed as ready before the script assets have been loaded depending on the size of the script file.

However $().ready() is now defined as not recommended by jQuery so use $(function(){}) instead.

John
  • 1,268
  • 16
  • 25
-1

$(window).on('load', function () {}) will guarantee that all resources loaded, not scripts only.

But why do you need that all script must be loaded? Scripts executes synchronously (without defer, async and lazy load technics), and if one of scripts is not loaded the browser engine will wait for it and after it loaded it will continue execution. To prevent this waiting of browser engine is one of main target client-side optimization. You can try to add all scripts to one file, for example.

Alex
  • 11,115
  • 12
  • 51
  • 64