473,738 Members | 9,555 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamicaly create javascript file and cache on client

I want to dynamically create a JavaScript file and cache it on the client
for re-use. I know how to write javascript to a web page from the code
behind, but I don't know how to actually create a file such as
MyNewScript.js and then cache that on the client so all the pages of that
session can use it. Can this be done?

Thanks

--
mo*******@nospa m.com
Nov 18 '05 #1
7 7768
If I am understanding correctly what you are looking for, just put:
<script language="javas cript" src="myjavascri ptfile.js"
type="text/javascript"></script>

in your head section. That should load and cache you javascript file.

--
Rocky Moore
www.HintsAndTips.com - Share your tips with the world!
~~~~~~~~~ Developer Tips Welcome! ~~~~~~~~~

"moondaddy" <mo*******@nosp am.com> wrote in message
news:ON******** ******@TK2MSFTN GP11.phx.gbl...
I want to dynamically create a JavaScript file and cache it on the client
for re-use. I know how to write javascript to a web page from the code
behind, but I don't know how to actually create a file such as
MyNewScript.js and then cache that on the client so all the pages of that
session can use it. Can this be done?

Thanks

--
mo*******@nospa m.com

Nov 18 '05 #2
Hi moondaddy,

Thanks for posting in the community!
From your description, you'd like to dynamically specify a js file for a
script block on a page so as to cache this js file to be used by other
pages,yes?
If there is anything I misunderstood, please feel free to let me know.

As for this question, here is my understanding:
1. I agree with Rocky that you can use either Response.Write or
Page.RegisterSc riptBlock to add a script specification as below:
<script language="javas cript" src="commonjsfi le.js"
type="text/javascript"></script>

Then, if the

2. You mean that you'd like to dynamically create the js file, do you mean
that you want to create a certain "*.js" file at runtime? For example when
the web application start? If so, I think you can make use of the classes
in the "System.IO" namespace. Because create a ".js" file is as simple as
creating a txt file, the only different is that you need to write the
proper javascript code into it. Do you think so?
Please try out the preceding suggestions. If you have any questions or feel
anything unclear on my description, please feel free to post here.
Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #3
Thanks Steven.

I think #2 below is what I'm looking for, but here is why and you can
evaluate if this is the correct solution to the problem.

I have some script the needs to be dynamically created from time to time and
many different pages will need to use this script. so rather than using
"Page.RegisterS criptBlock" in the code behind and loading it with every
page, I would like to generate an actual file that all pages could reference
such as
<script language="JavaS cript" src="commonjsfi le.js"
type="text/JavaScript"></script>
I'm still a novice at web development so I need to ask; if I reference the
script file like this:
<script language="JavaS cript" src="commonjsfi le.js"
type="text/JavaScript"></script>
Then will every page that uses it during that session use one copy cached on
the client automatically? and therefore it will be transmitted across the
wire only one time?

Knowing this, please confirm if #2 is the best approach for this situaton.

Thanks again.

"Steven Cheng[MSFT]" <v-******@online.m icrosoft.com> wrote in message
news:1J******** ******@cpmsftng xa07.phx.gbl... Hi moondaddy,

Thanks for posting in the community!
From your description, you'd like to dynamically specify a js file for a
script block on a page so as to cache this js file to be used by other
pages,yes?
If there is anything I misunderstood, please feel free to let me know.

As for this question, here is my understanding:
1. I agree with Rocky that you can use either Response.Write or
Page.RegisterSc riptBlock to add a script specification as below:
<script language="javas cript" src="commonjsfi le.js"
type="text/javascript"></script>

Then, if the

2. You mean that you'd like to dynamically create the js file, do you mean
that you want to create a certain "*.js" file at runtime? For example when
the web application start? If so, I think you can make use of the classes
in the "System.IO" namespace. Because create a ".js" file is as simple as
creating a txt file, the only different is that you need to write the
proper javascript code into it. Do you think so?
Please try out the preceding suggestions. If you have any questions or feel anything unclear on my description, please feel free to post here.
Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #4
Hi Moondaddy,
Thanks for your response. Yes, you're right, when use the <script
src=".....js" ></script> block to link a js file, if multi pages has
referenced the same file( make sure that the absolute path on the server
are also same if you're using relative path to specify the js file in
multipages). When the first time the js file is referenced. It'll be
downloaded to the clientside browser's cache. Then, if the same page or
even other pages refernce the same js file, the browser will check the
file's url path and find the file has already been referenced so it'll
retrieve it from the client's browser cache rather than request it again
from the serverside. Is this feature what you want?
Also, here is a tech artile in MSDN which has discussed the similar
siutaion to this:
#Creating a Web Part with Client-side Script
http://msdn.microsoft.com/library/en...lientScript.as
p?frame=true

In addtion, since the browser will always use the cached file if you hard
code the js file's path such as
<script language=javasc ript src=common.js ></script>. So there'll cause
some trouble if the js file on the serverside has been changed and need
update(request again from the serverside). Here is a solution to it:

You can append a "version" or date information without defeating the point
of
cached .js files.

<script language="javas cript" src="common.js? version=2004011 51300"></script>

When file.js is modified, simply change the value of "version" to something
else. Then, since the browser find that the link src's value has changed,
it'll request the file again from serverside. Thus, you can dynamically
determine whether to update the js from serverside or still use the file in
cache. How do you think of this?
Also, I 've made a generic sample page to show the above means, here is the
page code;
---------------------------aspx page--------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>DynamicJ S</title>
<meta name="GENERATOR " Content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body onload="PopupMe ssage()">
<form id="Form1" method="post" runat="server">
<table width="500" align="center">
<tr>
<td>
<asp:TextBox id="txtJSVersio n" runat="server"> </asp:TextBox></td>
</tr>
<tr>
<td>
<asp:Button id="btnPostBack " runat="server" Text="Post
Back"></asp:Button>
</td>
</tr>
</table>
</form>
</body>
</HTML>
---------------------code behind class---------------------------
public class DynamicJS : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Text Box txtJSVersion;
protected System.Web.UI.W ebControls.Butt on btnPostBack;
protected string scriptblock = "<script language='javas cript'
src='common.js? version={0}' ></script>";

private void Page_Load(objec t sender, System.EventArg s e)
{
if(!IsPostBack)
{
txtJSVersion.Te xt = DateTime.Now.To LongTimeString( );
string sb = String.Format(s criptblock,txtJ SVersion.Text);
Page.RegisterSt artupScript("dy namicscript",sb );
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
InitializeCompo nent();
base.OnInit(e);
}

private void InitializeCompo nent()
{
this.btnPostBac k.Click += new
System.EventHan dler(this.btnPo stBack_Click);
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion

private void btnPostBack_Cli ck(object sender, System.EventArg s e)
{
string sb = String.Format(s criptblock,txtJ SVersion.Text);
Page.RegisterSt artupScript("dy namicscript",sb );
}
}

---------------------------the "common.js" file-----------------------------
function PopupMessage()
{
alert("Hello World!");
}

---------------------------------
In this sample page, I put a textbox on the page to let user input a
version number, when the version number remains the same, the page will
always use the common.js in the client browser's cache. If we change the
value in the txtbox, it'll request the linked "common.js" from serverside
again. You can try modifying the common.js in half and unchange the
txtbox's value and post back the page, you'll find the popup message
remains the old. If you change the txtbox's value , then post back again,
the message will get changed(which means it update the js file in client
cache from serverside).

Please try out the preceding suggestions. If you feel anything unclear,
please feel free to let me know.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
Nov 18 '05 #5
Steven, I'm going to try your 2nd recommendation below and am trying to
create a sample text file but I get an error:
Access to the path "C:\CharmPi x" is denied.

What The error should say something like it cant find this file, but I guess
the security error runs first. My real problem is that I cant determine the
path where the project is running at run time

The project on the dev machine where the project is located in:
C:\Inetpub\wwwr oot\CharmPix

How can I determine the path of my of my project so I can create and save a
script file to the HD? When I run this on the production machine I wont
know the physical path of my site.

Public Sub Test2_MakeFile( )
' Dim sFile As String = Directory.GetCu rrentDirectory & "\MyFile.tx t"
' Dim sFile As String = "C:\Inetpub\www root\CharmPix\M yFile.txt"
'Dim sFile As String = "/CharmPix/MyFilexz.txt"
Dim sFile As String = HttpContext.Cur rent.Request.Ap plicationPath()
If File.Exists(sFi le) Then
Console.WriteLi ne("{0} already exists.", sFile)
Return
End If
Dim sr As StreamWriter = File.CreateText (sFile)
sr.WriteLine("T his is my file.")
sr.WriteLine("I can write ints {0} or floats {1}, and so on.", 1, 4.2)
sr.Close()
End Sub


--
mo*******@nospa m.com
"Steven Cheng[MSFT]" <v-******@online.m icrosoft.com> wrote in message
news:1J******** ******@cpmsftng xa07.phx.gbl...
Hi moondaddy,

Thanks for posting in the community!
From your description, you'd like to dynamically specify a js file for a
script block on a page so as to cache this js file to be used by other
pages,yes?
If there is anything I misunderstood, please feel free to let me know.

As for this question, here is my understanding:
1. I agree with Rocky that you can use either Response.Write or
Page.RegisterSc riptBlock to add a script specification as below:
<script language="javas cript" src="commonjsfi le.js"
type="text/javascript"></script>

Then, if the

2. You mean that you'd like to dynamically create the js file, do you mean
that you want to create a certain "*.js" file at runtime? For example when
the web application start? If so, I think you can make use of the classes
in the "System.IO" namespace. Because create a ".js" file is as simple as
creating a txt file, the only different is that you need to write the
proper javascript code into it. Do you think so?
Please try out the preceding suggestions. If you have any questions or feel anything unclear on my description, please feel free to post here.
Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #6
Hi Moondaddy,
Thanks for your followup. As for the latest problems you mentioned in the
reply, here are my suggestions on them:
1. Since the ASP.NET is running under some certain limited account(such as
MACHINE\ASPNET) by default , it hasn't the proper permissions of many
other folders such as create, remove... . So the first "Access Denied "
Error is cause by this, you need to provide the certain account (by default
is the MACHINE\ASPNET) enough privileges to a directory if you'd like to do
some certain operatoins(crea te ,remove or modify) on it.

2. As for how to determine the physical path in ASP.NET runtime via code, I
think you can use the Server.MapPath( ) method which take a string param(
specify the relative web path). For example, you can try the following code
in your web app:

//get the current asp.net page's current path's physical path
Response.Write( "<br>CurrentPat h: " + Server.MapPath( "."));
//get the website 's root 's physical path
Response.Write( "<br>RootPa th: " + Server.MapPath( "/"));
// get the current web page's parent folder's physical path
Response.Write( "<br>ParentPath : " + Server.MapPath( "../"));

Please try out the preceding means to see whether they're helpful. If you
have any further questions, please feel free to post here.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #7
Hi Moondaddy,
Have you had a chance to try out the latest suggestion in my last reply or
have you got any further ideas yourself? If you have any questions, please
feel free to let me know.
Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx

Nov 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2456
by: Ali Asghar | last post by:
Hi, Please I need help.I have a problem of client side XSL transformation. I sent the XML and the XSL to the client in XML data islands. Using the transform Node method the HTML is returned. There is however some script tag in the XSL file which references external ..js files they are like <SCRIPT language="Javascript" src="abc.js" DEFER="true" /> Now, after transformation the function from this .js file are not
5
5543
by: Larry Neylon | last post by:
Hi, I am having problems with our IIS6 server serving out of date javascript files in our ASP scripts. It appears to be an intermittent problem, but causes all kinds of headaches when working on javascript code. Is there any way of setting a Javascript file to always expired ?
2
1670
by: Lawrence San | last post by:
I'm trying to test some simple JavaScript meant to speed up the display of my Web pages for readers using modems, but I have a fast DSL connection and I'm having trouble visualizing how effective the code is. Does anybody know of software that will simulate modem speed over a DSL connection -- i.e., temporarily slow down the speed of my connection, or the speed at which the browser uses the connection? (I author on a Mac but test on a PC...
6
1862
by: KKramsch | last post by:
OK, here's the scenario: I have a CGI script that generates a page with frames (BTW, I'm not crazy about frames, but in this case the decision to use them is out of my hands). In a typical session, the user interacts with two of these frames extensively, and up to the very end of the session, this interaction is handled entirely client-side by a fairly elaborate JavaScript script. (This interaction takes place exclusively via HTML...
1
2082
by: Nathan | last post by:
We are encountering strange errors using IE 6 with a specified automatic configuration script and an internal ASP.NET application. The application performs very oddly throwing JavaScript errors all over the place. The JS errors are all in the built in .NET JavaScripts: wwwroot\aspnet_client\system_web\1_0_3705_288\WebUIValidation.js and wwwroot\aspnet_client\system_web\1_0_3705_288\SmartNav.js most of them are "Permission denied"...
3
1719
by: Joseph Ferris | last post by:
Hello everyone. I recently reloaded my system, and I am now having problems getting one of my client's sites running. I pulled a copy of the development tree for the project out of subVersion (the source control software we are using) and placed it into the IIS Web Root. After building and attempting to run the Solution, I am having problems with included Javascript files. How it is set up is that we have some .js files that have...
17
4892
by: shineofleo | last post by:
Here is the situation: I wrote a VB programm, which stores all the information in a single Access database file using jet engine. It worked well, however one of my customs reported that there was some problems with this programm. I checked, the log files showed that the database was corrupted. The customer told me that there no 'illegal' operation such as pull out the plug, or kill the programm via task manager... So is there any...
47
65383
by: SOLAV | last post by:
This is the only working way to completely hide your JavaScript code from the client just like PHP or ASP code. Here we'll need the help of PHP. Here is the code: index.php ________________________________________________________ <?PHP @session_start(); //Start our session. if(@!session_is_registered('PrintTheJavaScript')){ //If the session is not registered (and it's not). @session_register('PrintTheJavaScript'); //Register the...
0
8969
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8788
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9335
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9263
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9208
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6751
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2745
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.