Dynamically include client-side javascript

K

Kevin Spencer

Page.RegisterStartupScript(Key, ScriptString)
Page.RegisterClientScriptBlock(Key, ScriptString)

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 
A

Andrea Williams

I have a debug component that writes certain info into a DIV so that I can
see the things I need to debug the production server (It's only enabled for
my IP address). I also have client-side JavaScript that floats this div on
top of everything else in the browser and keeps it al the bottom of the
browser when I scroll it. My Debug component writes the JavaScript needed
to start the Floating script.

Right now, I have a component that all my pages inherit from that uses this
Debug class and automatically generates the div and start code when the
Debug config is enabled. However, I still have to add a JavaScript <script>
tag to every page and I would like to be able to do this in the debug class
so that I don't have to worry about adding the code
<script src="include/FloatDebug.js" language="javascript"></script>

to each page.

Is there a good way to add the js code from my class to the page without
doing a Response.write for every line? The js file code may change, so I
don't want to hard-code it into the class.

Also pages may be in a different folders of the application, so simply
writing the about code in a response.write, won't necessarily work.

Anyone have any ideas?? Is there a way to read the js file to the browser,
or somehow include it from my class, relative to the class instead of the
page? Writing it to the browser is the only way I can think of getting what
I'm going to need, right now. However, I don't particularly like to expose
the client side code on the page itself either, but I could live with that
if it would accomplish my goal.

Thanks in Advance!
Andrea
 
H

Hugo Wetterberg

You could read the script from disk instead of hard-coding it and
register it as a client script instead of using Response.WriteLine,
which always is a good idea. Because it is often used you could add
the script to cache instead of reading it from disk every time.

if(!Page.IsClientScriptBlockRegistered("myFunctionKey"))
{
FileInfo scriptFile=new FileInfo(MapPath("/scripts/float.js"));

if(scriptFile.Exists)
{
StreamReader reader=new StreamReader(scriptFile.FullName,true);
try
{
string script=string.Format(
"<script language='javascript'><!-- {0} --></script>",
reader.ReadToEnd());

Page.RegisterClientScriptBlock("floatKey",script);
}
finally
{
reader.Close();
}
}
}

/Hugo
 
A

Andrea Williams

I see how this could be advantagious! I didn't know I could do that...

THANKS!
Andrea
 

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

Top