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

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.