Using external js files

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

    Using external js files

    I'm a newbie who needs advice about how to use external files of JavaScript
    code. I spent an hour this afternoon browsing through JavaScript books at
    the local book store. In about 15 different titles, I found a total of about
    five pages that covered js files. For all practical purposes, these pages
    said, "You can use js files. But we won't tell you how."

    Therefore, I hope someone can answer a few questions about js files...

    1. JavaScript on a web page has un-named routines, and named functions. Can
    we name those un-named routines and put them into a js file? If so, are they
    also defined as functions? Or do we use some other key word to define such
    routines? Can JS functions do everything that the un-named routines can do?
    That is, can we call the un-named routines a function even though we don't
    care what value they return?

    2. Is program flow an issue? That is, does html wait for a JS function to be
    called?

    3. Logically, we could have many functions in one js file, or one function
    in each of many js files. Other than ease of programming and use, why would
    I choose one approach rather than the other?

    4. Within an html page, variables in un-named routines appear to have
    page-level scope. So to define a page-level variable in a js file, do we
    just declare variables at the top of the page outside a routine, as in a VB
    module?

    5. Do js files stay in memory until the browser is closed? If so, that would
    imply that page-specific code should remain with the page, rather than be
    moved to a js file. Or is there a way to close a specific js module when an
    html page is closed?

    6. Can a routine in one js file call a function in another js file--assuming
    that both files are declared with <SCRIPT src="whatever"> ?

    Thanks.

    Charley


  • Robert

    #2
    Re: Using external js files

    In article <1071aa272tvck5 0@corp.supernew s.com>,
    "Charley Kyd" <Kyd@IncSight.c om> wrote:
    [color=blue]
    > I'm a newbie who needs advice about how to use external files of JavaScript
    > code. I spent an hour this afternoon browsing through JavaScript books at
    > the local book store. In about 15 different titles, I found a total of about
    > five pages that covered js files. For all practical purposes, these pages
    > said, "You can use js files. But we won't tell you how."
    >[/color]

    Actually, the easiest thing to do is to put the javascript functions in
    the header section of an HTML file. You then call the functions from the
    body of the HTML file. You don't have to use an include file of
    Javascript unless you want too.


    Here are some html and javascript files that may provide some insight
    into your questions.

    Please place all these files in the same folder.

    Robert

    main.html:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <HTML>
    <HEAD>
    <TITLE>Simple Javascript Include</TITLE>
    <script type="text/javascript" src="first.js"> </script>
    <script type="text/javascript" src="second.js" ></script>
    </HEAD>
    <BODY>
    <SCRIPT LANGUAGE="JavaS cript">
    simpleAlert();
    callSecond("Ple ase display this.");
    </script>
    This HTML file should display an alert from a Javascript include file.
    <script type="text/javascript" src="inline.js" ></script>
    </BODY>
    </HTML>


    first.js:
    //
    // Common Functions:
    //

    var ourData = "Global variable data";

    function simpleAlert()
    {
    alert("This message came from a Javascript include file.");
    }

    function callSecond(pass edMessage)
    {
    messageAlert(pa ssedMessage);
    var localData = "This data variable is local to callSecond";
    messageAlert(lo calData);
    }

    second.js:
    //
    // Common Function:
    //



    function messageAlert(th eMessage)
    {
    alert(theMessag e);
    }


    inline.js:
    //
    // Insert a paragraph
    //


    document.write( "<p>Insert a paragraph from Javascript.<\/p>");

    alert(ourData);

    document.write( "<p>Insert a paragraph with " + ourData);
    document.write( " and notice the delay in displaying ");
    document.write( "this paragraph<\/p>");

    Comment

    • Charley Kyd

      #3
      Re: Using external js files

      "Robert" <rccharles@my-deja.com> wrote in message
      news:rccharles-696B9F.23193604 042004@news2.we st.earthlink.ne t...[color=blue]
      > In article <1071aa272tvck5 0@corp.supernew s.com>,
      > "Charley Kyd" <Kyd@IncSight.c om> wrote:
      >[color=green]
      > > I'm a newbie who needs advice about how to use external files of[/color][/color]
      JavaScript[color=blue][color=green]
      > > code. I spent an hour this afternoon browsing through JavaScript books[/color][/color]
      at[color=blue][color=green]
      > > the local book store. In about 15 different titles, I found a total of[/color][/color]
      about[color=blue][color=green]
      > > five pages that covered js files. For all practical purposes, these[/color][/color]
      pages[color=blue][color=green]
      > > said, "You can use js files. But we won't tell you how."
      > >[/color]
      >
      > Actually, the easiest thing to do is to put the javascript functions in
      > the header section of an HTML file. You then call the functions from the
      > body of the HTML file. You don't have to use an include file of
      > Javascript unless you want too.
      >
      >
      > Here are some html and javascript files that may provide some insight
      > into your questions.
      >
      > Please place all these files in the same folder.
      >
      > Robert
      >
      > main.html:
      > <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
      > <HTML>
      > <HEAD>
      > <TITLE>Simple Javascript Include</TITLE>
      > <script type="text/javascript" src="first.js"> </script>
      > <script type="text/javascript" src="second.js" ></script>
      > </HEAD>
      > <BODY>
      > <SCRIPT LANGUAGE="JavaS cript">
      > simpleAlert();
      > callSecond("Ple ase display this.");
      > </script>
      > This HTML file should display an alert from a Javascript include file.
      > <script type="text/javascript" src="inline.js" ></script>
      > </BODY>
      > </HTML>
      >
      >
      > first.js:
      > //
      > // Common Functions:
      > //
      >
      > var ourData = "Global variable data";
      >
      > function simpleAlert()
      > {
      > alert("This message came from a Javascript include file.");
      > }
      >
      > function callSecond(pass edMessage)
      > {
      > messageAlert(pa ssedMessage);
      > var localData = "This data variable is local to callSecond";
      > messageAlert(lo calData);
      > }
      >
      > second.js:
      > //
      > // Common Function:
      > //
      >
      >
      >
      > function messageAlert(th eMessage)
      > {
      > alert(theMessag e);
      > }
      >
      >
      > inline.js:
      > //
      > // Insert a paragraph
      > //
      >
      >
      > document.write( "<p>Insert a paragraph from Javascript.<\/p>");
      >
      > alert(ourData);
      >
      > document.write( "<p>Insert a paragraph with " + ourData);
      > document.write( " and notice the delay in displaying ");
      > document.write( "this paragraph<\/p>");[/color]

      Robert,

      Why would I ever want to maintain dozens of instances of the same code in
      dozens of web pages? I ***want*** to use an include file.

      Charley


      Comment

      • Richard Cornford

        #4
        Re: Using external js files

        Charley Kyd wrote:
        <snip>[color=blue]
        > Therefore, I hope someone can answer a few questions about js files...
        >
        > 1. JavaScript on a web page has un-named routines,[/color]

        By which I assume you mean global code (that is executed inline).
        [color=blue]
        > and named functions.[/color]

        Functions can be anonymous (though it would probably be best to ignore
        that fact for the time being).
        [color=blue]
        > Can we name those un-named routines and put them into a js
        > file?[/color]

        You can put global code that will be executed inline into an external JS
        file. Considerations of "naming" those "routines" will only confuse the
        issue. If you want to execute code as - someName() - it will have to be
        a function.
        [color=blue]
        > If so, are they also defined as functions? Or do we use some
        > other key word to define such routines?[/color]
        [color=blue]
        > Can JS functions do
        > everything that the un-named routines can do?[/color]

        Everything that can be done form global code can also be done form
        within a function.
        [color=blue]
        > That is, can we call
        > the un-named routines a function even though we
        > don't care what value they return?[/color]

        Global code is global code and a function is a function. Return values
        don't define functions (beyond that fact that functions have implicit
        undefined return values if they don't have an explicit return
        statement).
        [color=blue]
        > 2. Is program flow an issue?[/color]

        Yes.
        [color=blue]
        > That is, does html wait for a JS
        > function to be called?[/color]

        When a function is called an execution context is created for that
        function and execution enters that execution context until the function
        returns.

        HTML, as such, doesn't "do" anything so it cannot be said to "wait". The
        parsing of HTML source should not continue during the evaluation of a
        script element unless the script element has a DEFER attribute (else
        document.write calls would produce chaotic results).
        [color=blue]
        > 3. Logically, we could have many functions in one js file, or one
        > function in each of many js files. Other than ease of programming and
        > use, why would I choose one approach rather than the other?[/color]

        Each request to a server carries an overhead, fewer files reduces the
        overhead.
        [color=blue]
        > 4. Within an html page, variables in un-named routines appear to have
        > page-level scope.[/color]

        Global scope. The global object is the window or frame in a web browser,
        so if a frameset page was considered a page the resulting javascript
        environment would have multiple global objects (in a hierarchy
        reflecting the structure of resulting frames). For a non-frameset page,
        one page would be in one window and there would be one global object
        corresponding with that one window and so only one global scope.
        [color=blue]
        > So to define a page-level variable in a js file, do
        > we just declare variables at the top of the page outside a routine,[/color]

        The location of a variable declaration makes no difference to
        javascript. "Variable instantiation" (the creation of named properties
        of the "Variable" object belonging to the execution context) precedes
        the execution of code (global code or function body code depending on
        whether the execution is of global code or a function). Good form
        suggests that variable declarations should come before code that is to
        be executed.

        Using the - var - keyword to declare a variable in global code results
        in a global variable being created.
        [color=blue]
        > as in a VB module?[/color]

        That question pre-supposes familiarity with VB.
        [color=blue]
        > 5. Do js files stay in memory until the browser is closed?[/color]

        Who could say? It would be wasteful if they did.
        [color=blue]
        > If so,
        > that would imply that page-specific code should remain with the page,[/color]

        It is as likely that an HTML source file would stay in memory for as
        long as a JS source file.
        [color=blue]
        > rather than be moved to a js file. Or is there a way to close a
        > specific js module when an html page is closed?[/color]

        js module?
        [color=blue]
        > 6. Can a routine in one js file call a function in another js
        > file--assuming that both files are declared with <SCRIPT
        > src="whatever"> ?[/color]

        If the function that has been called is defined in a file that has
        already been loded.

        The difference between a script element that include the script as its
        contents and a script element that imports a script with its - src -
        attribute is nothing more than the location of the script's source code.
        Evaluation and execution of the script happens in exactly the same way
        and in exactly the same context.

        Generally it is better to import scripts than include them in HTML page
        source. It certainly makes the code more re-usable, takes advantage of
        the potential for caching on the client and avoids burdening javascript
        disabled/incapable browsers with downloading code that they will never
        execute.

        Richard.


        Comment

        • Chris Hope

          #5
          Re: Using external js files

          Charley Kyd wrote:
          [color=blue]
          > 1. JavaScript on a web page has un-named routines, and named functions.
          > Can we name those un-named routines and put them into a js file? If so,
          > are they also defined as functions? Or do we use some other key word to
          > define such routines? Can JS functions do everything that the un-named
          > routines can do? That is, can we call the un-named routines a function
          > even though we don't care what value they return?[/color]

          What do you mean by un-named routines? Do you mean code that isn't in a
          function? You should really put all stuff in a .js file in functions.
          Otherwise AFAIK it will run the code as soon as the .js file is loaded.
          [color=blue]
          > 2. Is program flow an issue? That is, does html wait for a JS function to
          > be called?[/color]

          It depends what your programming code does :) If you have a function in the
          page that is executed when the user interacts with an element in the page
          it will execute the function if it can find it. If the .js file has not yet
          loaded then the function won't yet exist so cannot be called and you'll get
          an error.
          [color=blue]
          > 3. Logically, we could have many functions in one js file, or one function
          > in each of many js files. Other than ease of programming and use, why
          > would I choose one approach rather than the other?[/color]

          Probably best to have one file with all the stuff, so only one file has to
          be downloaded (it will be cached so further requests in the site won't need
          to download it again). If you have separate sections that do different
          stuff then you might consider different .js files for the different areas.
          [color=blue]
          > 4. Within an html page, variables in un-named routines appear to have
          > page-level scope. So to define a page-level variable in a js file, do we
          > just declare variables at the top of the page outside a routine, as in a
          > VB module?[/color]

          Declaring variables in the .js file means they have scope for the page.
          However, if you try to reference one of those vars before the .js file is
          loaded you'll get an error.
          [color=blue]
          > 5. Do js files stay in memory until the browser is closed? If so, that
          > would imply that page-specific code should remain with the page, rather
          > than be moved to a js file. Or is there a way to close a specific js
          > module when an html page is closed?[/color]

          They won't stay in memory. They may remain cached so they don't get
          downloaded again. Depends on the browser and cache settings.
          [color=blue]
          > 6. Can a routine in one js file call a function in another js
          > file--assuming that both files are declared with <SCRIPT src="whatever"> ?[/color]

          Yes. As long as they are both loaded.

          HTH

          Chris

          --
          Chris Hope
          The Electric Toolbox Ltd

          Comment

          • Chris Hope

            #6
            Re: Using external js files

            Charley Kyd wrote:

            Forgot to mention in my other post... if you have stuff in your .js files
            such as DHTML menu with mouseovers etc the file may get to several kb in
            size and you may not want to execute anything until everything has loaded.

            You can use the <body> tag's onload value to call a function which enables
            your functionality. This function won't get executed until everything in
            the page has loaded, including all external files (images, css, js files
            etc).

            Chris

            --
            Chris Hope
            The Electric Toolbox Ltd

            Comment

            • Dr John Stockton

              #7
              Re: Using external js files

              JRS: In article <1071aa272tvck5 0@corp.supernew s.com>, seen in
              news:comp.lang. javascript, Charley Kyd <Kyd@IncSight.c om> posted at Sun,
              4 Apr 2004 17:33:00 :
              [color=blue]
              >I'm a newbie who needs advice about how to use external files of JavaScript
              >code.[/color]

              <URL:http://www.merlyn.demo n.co.uk/js-nclds.htm>
              <URL:http://www.merlyn.demo n.co.uk/js-other.htm>

              --
              © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
              <URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
              <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
              <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

              Comment

              • Robert

                #8
                Re: Using external js files

                "Charley Kyd" <Kyd@IncSight.c om> wrote in message news:<1071p3u7m 3vaof4@corp.sup ernews.com>...[color=blue]
                > "Robert" <rccharles@my-deja.com> wrote in message
                > news:rccharles-696B9F.23193604 042004@news2.we st.earthlink.ne t...[color=green]
                > > In article <1071aa272tvck5 0@corp.supernew s.com>,
                > > "Charley Kyd" <Kyd@IncSight.c om> wrote:
                > >[color=darkred]
                > > > I'm a newbie who needs advice about how to use external files of[/color][/color]
                > JavaScript[/color]
                [color=blue]
                >
                > Why would I ever want to maintain dozens of instances of the same code in
                > dozens of web pages? I ***want*** to use an include file.
                >
                > Charley[/color]

                Didn't know you had multiple pages

                I do not know all the details, and this could be alarmist, but see:

                Covers the how's and why's of Web caching for people who publish on the Web. With FAQs.


                Robert

                Comment

                • Chris Hope

                  #9
                  Re: Using external js files

                  Robert wrote:
                  [color=blue]
                  > http://www.mnot.net/cache_docs/[/color]

                  Thessentially good overview of what caching is etc etc. This is an issue you
                  always face when storing Javascript in external files: when you change the
                  code in the file the browser may/will continue to retain its cached version
                  of the file, even if it's been a couple of days since they last visited the
                  site.

                  Whenever I make major changes to an external Javascript library file I tend
                  to change its name eg from functions.js to functions2.js and update all the
                  relevant pages with the new filename. This can be a real pain if you have a
                  whole bunch of static HTML pages but it may be essential if your site will
                  break because the old functionality is wrong.

                  Should you still use external files? They are often essential to cut down
                  download times. If you have eg 4k of functions you don't want to bog down
                  your HTML pages with an extra 4k of Javascript functions everytime the
                  pages is loaded and it becomes a nightmare updating scripts when you want
                  to change the functionality. It's just like CSS - would you really put all
                  your CSS inline in a page or in an external file?

                  Chris

                  --
                  Chris Hope
                  The Electric Toolbox Ltd

                  Comment

                  • Charley Kyd

                    #10
                    Re: Using external js files

                    Thanks for all your advice.

                    Charley


                    Comment

                    Working...