473,399 Members | 3,302 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

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
Jul 23 '05 #1
9 6877
In article <10*************@corp.supernews.com>,
"Charley Kyd" <Ky*@IncSight.com> wrote:
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."


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="JavaScript">
simpleAlert();
callSecond("Please 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(passedMessage)
{
messageAlert(passedMessage);
var localData = "This data variable is local to callSecond";
messageAlert(localData);
}

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

function messageAlert(theMessage)
{
alert(theMessage);
}
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>");
Jul 23 '05 #2
"Robert" <rc*******@my-deja.com> wrote in message
news:rc*****************************@news2.west.ea rthlink.net...
In article <10*************@corp.supernews.com>,
"Charley Kyd" <Ky*@IncSight.com> wrote:
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."


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="JavaScript">
simpleAlert();
callSecond("Please 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(passedMessage)
{
messageAlert(passedMessage);
var localData = "This data variable is local to callSecond";
messageAlert(localData);
}

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

function messageAlert(theMessage)
{
alert(theMessage);
}
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>");


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
Jul 23 '05 #3
Charley Kyd wrote:
<snip>
Therefore, I hope someone can answer a few questions about js files...

1. JavaScript on a web page has un-named routines,
By which I assume you mean global code (that is executed inline).
and named functions.
Functions can be anonymous (though it would probably be best to ignore
that fact for the time being).
Can we name those un-named routines and put them into a js
file?
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.
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?
Everything that can be done form global code can also be done form
within a function.
That is, can we call
the un-named routines a function even though we
don't care what value they return?
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).
2. Is program flow an issue?
Yes.
That is, does html wait for a JS
function to be called?
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).
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?
Each request to a server carries an overhead, fewer files reduces the
overhead.
4. Within an html page, variables in un-named routines appear to have
page-level scope.
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.
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,
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.
as in a VB module?
That question pre-supposes familiarity with VB.
5. Do js files stay in memory until the browser is closed?
Who could say? It would be wasteful if they did.
If so,
that would imply that page-specific code should remain with the page,
It is as likely that an HTML source file would stay in memory for as
long as a JS source file.
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?
js module?
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">?


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.
Jul 23 '05 #4
Charley Kyd wrote:
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?
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.
2. Is program flow an issue? That is, does html wait for a JS function to
be called?
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.
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?
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.
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?
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.
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?
They won't stay in memory. They may remain cached so they don't get
downloaded again. Depends on the browser and cache settings.
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">?


Yes. As long as they are both loaded.

HTH

Chris

--
Chris Hope
The Electric Toolbox Ltd
http://www.electrictoolbox.com/
Jul 23 '05 #5
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
http://www.electrictoolbox.com/
Jul 23 '05 #6
JRS: In article <10*************@corp.supernews.com>, seen in
news:comp.lang.javascript, Charley Kyd <Ky*@IncSight.com> posted at Sun,
4 Apr 2004 17:33:00 :
I'm a newbie who needs advice about how to use external files of JavaScript
code.


<URL:http://www.merlyn.demon.co.uk/js-nclds.htm>
<URL:http://www.merlyn.demon.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.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #7
"Charley Kyd" <Ky*@IncSight.com> wrote in message news:<10*************@corp.supernews.com>...
"Robert" <rc*******@my-deja.com> wrote in message
news:rc*****************************@news2.west.ea rthlink.net...
In article <10*************@corp.supernews.com>,
"Charley Kyd" <Ky*@IncSight.com> wrote:
I'm a newbie who needs advice about how to use external files of
JavaScript


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


Didn't know you had multiple pages

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

http://www.mnot.net/cache_docs/

Robert
Jul 23 '05 #8
Robert wrote:
http://www.mnot.net/cache_docs/


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
http://www.electrictoolbox.com/
Jul 23 '05 #9
Thanks for all your advice.

Charley
Jul 23 '05 #10

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

Similar topics

0
by: Hans-Joachim Widmaier | last post by:
Hi, I have a class that reads most common files (text, images, tar archives, zip archives). I just read in the whole thing and decide then what to do with it - create a gtk.TextView, gdk.pixbuf,...
3
by: deanfamily11 | last post by:
I've got a program that uses functions to various tasks easily. How can I initalize input and output files outside of the main program?
0
by: David Helgason | last post by:
I think those best practices threads are a treat to follow (might even consider archiving some of them in a sort of best-practices faq), so here's one more. In coding an game asset server I want...
4
by: planetthoughtful | last post by:
Hi All, Just wondering if anyone can tell me if it's possible to programatically save Access2003 code (ie code behind forms, as well as class modules) to external files? I'd like to use...
1
by: MaxWall | last post by:
Hi Everyone, I'm new to the forum and to the Actionscripting world. I need some help with a project I'm working on and would appreciate any guidance. I'm working on a flash app for CD-ROM...
4
by: Kanuk | last post by:
I know there has to be a way to do this I want to beable to store and input data from a txt file and then beable to load it and parce it into visual basic to be thrown into a 1,2,or 3 dimentinal...
1
by: Kanuk | last post by:
Im using Visual basic 2005 and i want to make the bulk of my data user editable in files such as txt or dat files (maybe even xml) My questions is how do i get the data from the file.. into an...
0
debasisdas
by: debasisdas | last post by:
This thread contains some useful tips for using External tables. USING EXTERNAL TABLE ======================= 1.THE TABLE POINTS TO EXTERNAL FILE. IF DATA IS ALTERED IN THE EXTERNAL FILE,DATA...
0
TjFL
by: TjFL | last post by:
I have a form where specific external files are selected by the user depending on needs. Each item listed on the form has 4 Yes/No boxes next to it where they select what they want. The result will...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...

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.