Page 1 of 1
Best way to use a JavaScript
Posted: Thu Dec 04, 2008 2:54 pm
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>
Re: Best way to use a JavaScript
Posted: Thu Dec 04, 2008 3:00 pm
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
})();
Re: Best way to use a JavaScript
Posted: Thu Dec 04, 2008 3:01 pm
by icesolid
?
Re: Best way to use a JavaScript
Posted: Thu Dec 04, 2008 3:24 pm
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.
Re: Best way to use a JavaScript
Posted: Sat Dec 06, 2008 6:01 am
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.
Re: Best way to use a JavaScript
Posted: Sat Dec 06, 2008 3:58 pm
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)