-3

I have read that for jQuery to work I have to have this code:

$(Document).ready(function(){
    //some code
)};

But I'm unsure which file is compiled first into application.js, so where do I have to put that code and how do I put all other files into that file?

Studocwho
  • 2,290
  • 3
  • 20
  • 27
onix
  • 17
  • 5

2 Answers2

0

Related: Why does jQuery or a DOM method such as getElementById not find the element?
Related: https://learn.jquery.com/using-jquery-core/document-ready/

The purpose of a document ready is to allow you to include your script any where on the page, and javascript will delay its execution until the file markup has been fully parsed and loaded into the DOM. Images and other assets may not have loaded yet, but the document Elements will exist.

With that in mind, document ready is not a requirement. If you structure your document in the pattern than your javascript is included at the bottom of your page, or at least after all the elements it will attempt to reference, the document ready is not necessary. Once the elements are in the DOM, the javascript can find them.

Side note; Document in your snippet should be document as it is case sensative.

Taplar
  • 24,246
  • 4
  • 18
  • 33
  • I know why it doesn't work, i want to know where in RoR i have to put that line. To have better organisation i'm making a lot of .js files which are compiled in application.js. I want to know in which file do i have to pot that line or mby i can put somewhere else – onix Oct 14 '19 at 20:55
  • You don't put that line in one place, and it's not a "line". You wrap every piece of code you want to attach to the ready event in that structure. You reuse it as many times as you need to. If you want to put it in one place, then structure your code so that it has a single point of entry. – meager Oct 15 '19 at 01:40
0

You define the files included in application.js, you can require them explicitly if their loading sequence needs to be controlled. If you are using require tree the files are loaded in alphabetical order.

The strategy for using the jQuery ready pattern is normally to just use it to wrap an initialize() type of function call, where intialize is a function defined elsewhere in your js files. It can be difficult to read if you put lots of code inside the document ready wrapper, keep it simple. It's best to use just one document ready wrapper, so that you are sure of the initialization sequence.

Les Nightingill
  • 2,897
  • 1
  • 23
  • 25