Dynamicaly create javascript file and cache on client

M

moondaddy

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
 
R

Rocky Moore

If I am understanding correctly what you are looking for, just put:


<script language="javascript" src="myjavascriptfile.js"
type="text/javascript"></script>

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

Steven Cheng[MSFT]

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.RegisterScriptBlock to add a script specification as below:
<script language="javascript" src="commonjsfile.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.)
 
M

moondaddy

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.RegisterScriptBlock" 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="JavaScript" src="commonjsfile.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="JavaScript" src="commonjsfile.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.
 
S

Steven Cheng[MSFT]

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-us/spptsdk/html/CreateWPClientScript.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=javascript 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="javascript" src="common.js?version=200401151300"></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>DynamicJS</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body onload="PopupMessage()">
<form id="Form1" method="post" runat="server">
<table width="500" align="center">
<tr>
<td>
<asp:TextBox id="txtJSVersion" 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.Page
{
protected System.Web.UI.WebControls.TextBox txtJSVersion;
protected System.Web.UI.WebControls.Button btnPostBack;
protected string scriptblock = "<script language='javascript'
src='common.js?version={0}' ></script>";

private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
txtJSVersion.Text = DateTime.Now.ToLongTimeString();
string sb = String.Format(scriptblock,txtJSVersion.Text);
Page.RegisterStartupScript("dynamicscript",sb);
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.btnPostBack.Click += new
System.EventHandler(this.btnPostBack_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void btnPostBack_Click(object sender, System.EventArgs e)
{
string sb = String.Format(scriptblock,txtJSVersion.Text);
Page.RegisterStartupScript("dynamicscript",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.)
 
M

moondaddy

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:\CharmPix" 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\wwwroot\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.GetCurrentDirectory & "\MyFile.txt"
' Dim sFile As String = "C:\Inetpub\wwwroot\CharmPix\MyFile.txt"
'Dim sFile As String = "/CharmPix/MyFilexz.txt"
Dim sFile As String = HttpContext.Current.Request.ApplicationPath()
If File.Exists(sFile) Then
Console.WriteLine("{0} already exists.", sFile)
Return
End If
Dim sr As StreamWriter = File.CreateText(sFile)
sr.WriteLine("This is my file.")
sr.WriteLine("I can write ints {0} or floats {1}, and so on.", 1, 4.2)
sr.Close()
End Sub
 
S

Steven Cheng[MSFT]

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(create ,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>CurrentPath: " + Server.MapPath("."));
//get the website 's root 's physical path
Response.Write("<br>RootPath: " + 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.)
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top