Dynamicaly create javascript file and cache on client

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • moondaddy

    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

    --
    moondaddy@nospa m.com


  • Rocky Moore

    #2
    Re: Dynamicaly create javascript file and cache on client

    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" <moondaddy@nosp am.com> wrote in message
    news:ONNAnXu6DH A.3648@TK2MSFTN GP11.phx.gbl...[color=blue]
    > 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
    >
    > --
    > moondaddy@nospa m.com
    >
    >[/color]


    Comment

    • Steven Cheng[MSFT]

      #3
      RE: Dynamicaly create javascript file and cache on client

      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.)

      Comment

      • moondaddy

        #4
        Re: Dynamicaly create javascript file and cache on client

        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
        [color=blue]
        > <script language="JavaS cript" src="commonjsfi le.js"
        > type="text/JavaScript"></script>[/color]

        I'm still a novice at web development so I need to ask; if I reference the
        script file like this:
        [color=blue]
        > <script language="JavaS cript" src="commonjsfi le.js"
        > type="text/JavaScript"></script>[/color]

        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-schang@online.m icrosoft.com> wrote in message
        news:1J1pWex6DH A.3032@cpmsftng xa07.phx.gbl...[color=blue]
        > 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[/color]
        feel[color=blue]
        > 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.)
        >[/color]


        Comment

        • Steven Cheng[MSFT]

          #5
          Re: Dynamicaly create javascript file and cache on client

          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
          Find official documentation, practical know-how, and expert guidance for builders working and troubleshooting in Microsoft products.

          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.)


          Comment

          • moondaddy

            #6
            Re: Dynamicaly create javascript file and cache on client

            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








            --
            moondaddy@nospa m.com
            "Steven Cheng[MSFT]" <v-schang@online.m icrosoft.com> wrote in message
            news:1J1pWex6DH A.3032@cpmsftng xa07.phx.gbl...[color=blue]
            > 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[/color]
            feel[color=blue]
            > 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.)
            >[/color]


            Comment

            • Steven Cheng[MSFT]

              #7
              Re: Dynamicaly create javascript file and cache on client

              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.)

              Comment

              • Steven Cheng[MSFT]

                #8
                Re: Dynamicaly create javascript file and cache on client

                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
                Build web apps and services that run on Windows, Linux, and macOS using C#, HTML, CSS, and JavaScript. Get started for free on Windows, Linux, or macOS.


                Comment

                Working...