Monday, February 21, 2011

JavaScript how to use .js file

I'm sorry for this very newbish question I'm not much given into web development. I've got this cool javascript on a .js file that we want to use at a small web site. (It's a script to run piclens on it).

Can anyone point me some directions on how to use the .js file? Or how to attach it to my html code. Ty :)

If you feel this is a traditional "please read the manual" i would be happy 2 but haven't been able to find out how to do it :(

From stackoverflow
  • <script type="text/javascript" src="myfile.js"></script>
    

    Usually inserted in the <head> tag. After that, it depends wether or not your script need additional initialization or customisation to work.

    David Dorward : You are missing the (required) type attribute.
    matt lohkamp : type="text/javascript" very important.
    gizmo : This required type is useless. First of all JS is the only scripting language accros all the browser (VBS is IE only and nearly dead). Then you sould rely on the MIME type sent by the server and not by the one written in the tag.
    David Dorward : If nothing else, specifying the type stops validators from outputting an error. Having lots of errors that you don't care about makes it harder to find errors you DO care about.
    eyelidlessness : Insert before improves performance, and also allows DOM queries when script loads.
    gizmo : @eyelidlessness: You're right, except if the JS script has to do some DOM computation before that all the rest of the page is loaded. It was often the case with "old way" scripts.
  • See Using External ".js" Files to answer your specific question. Also suggest some tutorials, e.g.

    David Dorward : Avoid w3schools - they are full of errors.
  • Just include this line anywhere in your HTML page:

    <script type="text/javascript" src="yourfile.js"></script>
    

    Don't forget the closing tag as IE won't recongize it without a separate closing tag.

    David Dorward : In HTML the closing tag is required anyway. (In XHTML you can use empty element syntax if you use an XML content-type, but Appendix C "forbids" it for XHTML masquerading as HTML)
    DrJokepu : What I meant that even in XHTML, IE won't understand