Chi Chan
Chi Chan

Reputation: 12350

Best practice for organizing JavaScript coming back from Ajax calls

I am writing an application (Asp.Net MVC) that contains a lot of reusable components.

I am currently loading these components with Ajax calls, using the jQuery library of course.

These components will be calling other sub-components as well, and so there are all these JavaScript coming back.

So question is, where should I put the "callback" JavaScript?

I currently have something like this:

The page:

<html>
<head>
    <title>blah</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" ></script>
</head>
<body>

<div id="Container"></div>

<script type="text/javascript">
    $(document).ready(function() {
        $('#Container').load('SomeCrazyDomain.com/SomeComponent');
    });
</script>
</body>
</html>

The Component:

<p>Load sub components</p><input type="button" onclick="GetSubcompent" />
<div id="SubcompentContainer"></div>

<!-- Is this Bad? -->
<script type="text/javascript">
    function GetSubcompent() {
        $('#SubcompentContainer').load('SomeCrazyDomain.com/SomeSubComponent');
    }
</script>

The sub component:

<h1>I am a sub compent</h1>
<script type="text/javascript">
    function ToBeLoadedForEachAjaxCall() {
        //do something
    }
</script>

If, I leave it as it is, what's the effect of loading ToBeLoadedForEachAjaxCall() for each ajax call? Will the broswers kill the last ToBeLoadedForEachAjaxCall() and replace with the "newer" one?

Thank you,

Upvotes: 1

Views: 262

Answers (1)

Jey Balachandran
Jey Balachandran

Reputation: 3935

It is generally a bad idea to throw inline javascript into your markup. Makes maintenance and debugging very troublesome down the road. You should be creating a common js file that contains all the JavaScript code and include it in your <HEAD> or before the </BODY>. For example, have a js file that contains the following:

$('#SubcompentContainer').load('SomeCrazyDomain.com/SomeSubComponent');
function ToBeLoadedForEachAjaxCall() {
    //do something
}

Eventually, you might realize that some of this code is very specific to various sections of the site. You might not want to load SomeCrazyDomain.com/SomeSubComponent on each page. At this point you can choose to create js files specific to different sections of the site.

To answer your second question. If there are multiple javascript functions with the same name, the last one defined will be the one run.

Upvotes: 1

Related Questions