Skip to main content

The best way to write Javascript / jQuery



I'm not new to web dev but I was just wondering if you guys have some advice for me to improve:





Always when I write js or jQuery I write all the code like this in the <head> on my page:







<script>

$(document).ready(function() {



//All my functions and animations goes here…



});

</script>







Now, when I look around the web I see that most people have their functions and animations in a separate ".js"-file. And they often create classes aswell.





How does that work? What is the advantage of creating classes and have your functions in a separate file?





Thanks, VG


Comments

  1. Advantages of putting your javascript into a separate file:


    Reuse on multiple pages - You can more easily reuse the same javascript functions on multiple pages without having multiple separate copies of the code.
    More efficient caching - The browser can much more efficiently cache your javascript which can lead to faster page load times. When using an external JS file, it can be loaded upon first use and then retrieved from the browser cache for all subsequent page loads that use that same JS file.
    Separation of code from HTML - You get better separation of the different types of content on the page. The visual designer can work on the HTML while the software developer can work on the javascript and they are not working in the exactly same file.


    Note: for performance reasons, you don't want to have a lot of small, separate external JS files as it takes longer to load lots of small JS files than it does one larger JS file.

    Structuring code into classes/objects can have the following advantages:


    Organization - It forces the developer to organize their code into blocks of functionality where you have an object with a given set of methods and properties. For anything other than a trivial project, this is a much cleaner way or organizing things than just a big list of javascript functions.
    Encapsulation - Object oriented design causes you to put data into objects where it's much clearer who owns the data, who modifies the data, what it's lifetime is and what methods exist to modify the data. In addition, some data can be encapsulated inside the object so it can only be modified via the desired methods (not mucked with directly).
    Testing - it can be much easier to write test suites for code organized into objects, methods and properties.
    Self documenting - Code organized into objects, methods and properties is general much more self-documenting that a long list of procedures.
    Modularity - It is typically easier to break object-oriented code into reusable modules than code that is not organized this way.
    Extensibility - A good object oriented design can be much easier to extend and enhance through things like sub-classing and method overrides than straight procedural code.
    Maintainability - For all the above reasons, good object oriented code can be easier to maintain.


    FYI, many of the advantages of object oriented thinking and design can be found without using literal classes (which javascript doesn't even really have). It's more a matter of how you design and implement your code than it is a particular language syntax feature. For example, you can have an object oriented design in plain C which has no specific language concept of a class or object. In javascript lots of language elements are objects with extensible properties and methods so it's even easier to do object oriented design in javascript (in fact, it's hard to avoid doing it) because there are already objects all around you (the window object, all the DOM objects, etc...).

    ReplyDelete
  2. The advantage of putting your javascript code in separate files is that you no longer mix markup (which is what HTML is) and scripting. You have a clear separation of concerns. Same stands for CSS. Styling goes into separate files. As a result your markup becomes smaller. The javascript being static, client browsers are caching all those external static files. So they don't need to fetch it everytime a request is made. This improves the performance of your applications because there is less data to send over the wire. Only the markup that changes from page to page is retrieved from the server.

    As far as organizing your scripts into classes and functions, that's for better readability and reusability. When you are working on large projects with lots of javascript it is better if you could split it into separate modules so that those modules could be easier to maintain by different developers on the team.

    ReplyDelete
  3. Splitting up your classes and what not into separate files makes the more maintainable and more reuseable for other projects. It just keeps things organized.

    Beware though... you don't want to have a ton of files the client has to go download! Often times, something will be running server-side to assemble all of the relevant files into one download. PHP can do this for you easily.

    ReplyDelete
  4. In addition, implementing js Object classes helps avoid namespace collision with variable & function names... all in all, in my opinion a good practice to get into.

    ReplyDelete
  5. quite a lot of difference and better practice. But for example you whant that jquery function to be in another file you could write the code once. Also it will increase the speed of your website with having only to load the content once.

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex