[RESOLVED]Keeping JavaScript as all External Files

I have an MVC application with several Views.  Some of the Views include some JavaScript that ranges from a simple command to set the focus to some rather complex functions. The _Layout.cshtml file also includes a few JavaScript functions.  I have placed
the more complex functions that are shared by more than one View into the Scripts folder and add them to the page using a RenderScripts Razor command.  All other scripts are included on the View in the Scripts section beneath the @Scripts.Render("") commands.
 

Due to users being able to see the JavaScript, I am planning to move all my JavaScript to external files in the future.  There are two main architecture questions I have, however:

  1. How do I handle using document.ready() in both the _Layout.cshtml page and the specified View?  At the moment, I have calls in both places, but this seems inefficient and incorrect.
  2. Would it be advisable to create a JavaScript file for each View that contained the document.ready() for each View and then just load up the appropriate functions that are located in separate JavaScript files or is it better just to put the document.ready()
    function in each View?  I could write a generic document.ready() function for all the Views that do not include anything special.   

For example, having a bunch of JavaScript files that essentially look similar to this:

$(function () {
    $("#SelectedItem").focus();
    updateTopics();
});

versus having a script similar to the following at the bottom of each View:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/fixTopicData")
    @Scripts.Render("~/bundles/updateTopics")

    <script type="text/javascript">
        $(function () {
            $("#SelectedItem").focus();
            updateTopics();
        });
    </script>
}

Thank you for any suggestions!

$.ready was designed to called multiple times. you will lost of examples in the source code, and almost all plugins make a call. in javascript a function is an object, and it just added to a collection in $.ready() and executed after the dom event. see the
deferred object which is used as the collection.  

Thanks!  I did make a small change by creating a class that receives the focus instead of calling focus() based on the id for each page.  That allowed me to put the code for setting the focus into the _Layout.cshtml.

Leave a Reply