0

I am writing a one page web-application in JavaScript with jQuery. I add my JavaScript source and jQuery to the HTML page and register my function to be invoked when the the page is fully rendered.

<script type="text/javascript" src="lib/jquery-1.8.0.js"></script>
<script type="text/javascript" src="src/myapp.js"></script>
<script type="text/javascript">$(MyApp.onReady)</script>

It works but I do not like to have code inside HTML.

Now I wonder if I can get rid of the last line. Is it absolutely necessary to invoke $(MyApp.onReady) in the HTML?

Michael
  • 10,185
  • 12
  • 59
  • 110

6 Answers6

2

You can respond to a document.ready in your myapp.js file. This will ensure that the DOM tree is ready for use:

$(document).ready(function () {
    // do whatever you want here, confident that the DOM is loaded
});

If you need to wait until the entire page is rendered in the browser (images and such), you can respond to the load event:

$(window).load(function() {
    // everything is rendered in the browser
});

You usually do not need to wait until load, i would recommend trying the first snippet before resorting to the second.

jbabey
  • 45,965
  • 12
  • 71
  • 94
1

$(document).ready is called when all the rendering on html controls is completed, You can put your code in this method or call your method in it

$(document).ready(function(){
    //your code here
    //$(MyApp.onReady) 
});
Adil
  • 146,340
  • 25
  • 209
  • 204
1

You can place the $( MyApp.onReady ); line inside myapp.js. All you need to take care is to load jQuery before you load your file.

Grampa
  • 1,623
  • 10
  • 25
1

You can add this code to the tail of your myapp.js file like:

/* myapp.js */
var MyApp = (function(app, $) {
    // your logic...
    // defining app.onReady function...
    $(function() {
        app.onReady();
    });

    return app;
})(MyApp || {}, jQuery);
Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43
1

You need to call MyApp.onReady() somewhere. If you will be accessing the DOM (which you probably will be), yes, you must wait until the DOM is processed. You can avoid having to use document.ready by putting MyApp.onready() in a script right before the closing body tag. By then, the DOM will have already been parsed. However, if you aren't accessing the DOM, you can just do MyApp.onReady() anywhere.

Abraham
  • 20,316
  • 7
  • 33
  • 39
1

Take a look at this question: Running javascript after page is fully rendered

Basically, it looks like you want to set a function to window.onload, and this will run after the page has been rendered. Since I can't see your myapp.js, I don't know what the onReady function does there. Whether or not you keep that line depends on what that function does. As Grampa says, you can place that line in the javascript file though.

Community
  • 1
  • 1
mejdev
  • 3,509
  • 4
  • 24
  • 38