Best way to use a JavaScript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
icesolid
Forum Regular
Posts: 502
Joined: Mon May 06, 2002 9:36 pm
Location: Buffalo, NY

Best way to use a JavaScript

Post by icesolid »

What is the best way of using a JavaScript right within other code.

EX:

Code: Select all

<script type="text/javascript">
javascript code here
</script>
OR

Code: Select all

<script type="text/javascript">
<!--
javascript code here
//-->
</script>
OR

Code: Select all

<script type="text/javascript">
/* <![CDATA[ */
javascript code here
/* ]]> */
</script>
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Best way to use a JavaScript

Post by Eran »

Code: Select all

 
<script src="/path/to/script.js" type="text/javascript"></script>
 
And then:

Code: Select all

 
//script.js
 
;(function(){
   Javascript code goes here
})();
 
icesolid
Forum Regular
Posts: 502
Joined: Mon May 06, 2002 9:36 pm
Location: Buffalo, NY

Re: Best way to use a JavaScript

Post by icesolid »

?
User avatar
Syntac
Forum Contributor
Posts: 327
Joined: Sun Sep 14, 2008 7:59 pm

Re: Best way to use a JavaScript

Post by Syntac »

The best way of embedding JavaScript in a page is to keep it in an external file, so no matter what happens, it won't be displayed as text.
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Re: Best way to use a JavaScript

Post by JAB Creations »

pytrin is correct, in a live environment keep your JavaScript code in a separate file.

I'd like to add two things...

1.) While it is valid to have a script element within the body element I consider it unprofessional.

2.) The third example you posted is how you should do it for test cases when you want to edit a single file to test a script out on the same page you are executing the script on.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: Best way to use a JavaScript

Post by Kieran Huggins »

http://javascript.crockford.com/code.html
Douglas Crockford wrote: JavaScript programs should be stored in and delivered as .js files.

JavaScript code should not be embedded in HTML files unless the code is specific to a single session. Code in HTML adds significantly to pageweight with no opportunity for mitigation by caching and compression.

<script src=filename.js> tags should be placed as late in the body as possible. This reduces the effects of delays imposed by script loading on other page components. There is no need to use the language or type attributes. It is the server, not the script tag, that determines the MIME type.
(emphasis mine)
Post Reply