Karim Karim - 5 months ago 8
Javascript Question

a solution to include jquery & js in the end of the html while at the same time a control which is included in the middle requires $(document).ready

i am building a website using asp.net mvc and jquery.

as a best practice its known that including javascript should be done at the end of the html page.

so i basically include jquery.js and other js files in the end of the html before the /body tag.

now i have some controls which are included in the page as partials. and they need to add functionally to $(document).ready.

but i write the code as a script tag in the partial then the jquery library wont be even included at that time and i cant include this javascript at the end of the html from within the partial. since the partial is included in the middle of the html.


Move all javascript in single file(you may exclude jQuery file) and move it to the bottom.

If you are talking of good practice then, then writing inline javascript is not a good practice too.

So I would suggest move all your java script to single file,there are many tools available that merge multiple javascript files and crunch them, use those!!


You may try this:

//define this at before body (or at the beginning of body)
var arrReadyCollection = [];

Inside controllers:


At the end, after jQuery file

for (i=0;i<arrReadyCollection.length; i++)
     var fn= arrReadyCollection[i];

Note: this is not recommended way, its just way you can solve your problem