multiple javascript for user controls

G

Guest

Hi,
I have a usercontrol which includes a small piece of Javascript built up
as a string in <script> tags and put onto a web page when an instance of the
User Control is created. The Javascript does some client side checking of
User Input.

If I use multiple instances of the same user control on a page, the same
block of Javascript is repeatedly written to the page (once for each instance
of the user control). Although the user controls still work, it creates a
bigger page to download from the server.

Is ther any way of just writing the Javascript the once to the page? or is
there a better way of getting the Javascript written. (I wanted to keep the
Javascript integral to the user control so that it was independent).

Many thanks,

Pete
 
B

Brennan Stehling

Hi Italian Pete,

You can use an ASP.NET feature to register the scripts. You uniquely
identify them with keys.

Here is some example code.

string key = "script1";
string url = "scripts/script1.js";

if (!Page.ClientScript.IsClientScriptIncludeRegistered(key))
{
Page.ClientScript.RegisterClientScriptInclude(key, url);
}

That will ensure it is only included once per key.

You can also build an assembly which embeds the scripts you are using
to make it easy to deploy them with your website.

I created an assembly with a control to manage the scripts here...

http://svn.offwhite.net/svn/SmallSharpTools.EmbeddedScripts/trunk/

You can browse the code to see what I did there. It is a Subversion
repository so you could use TortoiseSVN to pull down the whole project
and work use it.

Brennan Stehling
http://brennan.offwhite.net/blog/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top