Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I include an external JavaScript file exactly once per partial view?

Tags:

I have a partial view (UserControl) that implements a simple pager in my Asp.Net MVC project. This pager needs access to a .js file that needs to be included exactly once, regardless of how many instances of the pager control are present on the parent page.

I've tried to use Page.ClientScript.RegisterClientScriptInclude, but it had no effect (I assume because the code nugget was evaluated too late to impact the head control). Is there any simple alternative?

like image 506
AaronSieb Avatar asked Mar 12 '10 03:03

AaronSieb


People also ask

Can you put JavaScript in a partial view?

JavaScript functions can be bound to elements on the partial view; the partial view is rendered at the same time as the parent view. This happens when loading the partial view with a @Html. Action helper method, as in this section from Edit.

How do I include an external JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Should JavaScript always be in a separate file?

You should put your JS code in a separate file because this makes it easier to test and develop. The question of how you serve the code is a different matter. Serving the HTML and the JS separately has the advantage that a client can cache the JS.

Should all my JavaScript be in one file?

To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file.


1 Answers

Set a flag in HttpContext.Current.Items when you send the script in your partial - it's a dictionary that lingers for the whole request. E.g.:

if (!HttpContext.Current.Items.Contains("SentTheScript"))
{
    HttpContext.Current.Items["SentTheScript"] = true;
    Response.Write(Html.ScriptTag("Script"));
}

This way it'll be rendered at most once.

like image 82
kevingessner Avatar answered Sep 28 '22 18:09

kevingessner