Modularize scripts of a website

Discussion in 'Web Design and Development' started by raison, Aug 2, 2016.

  1. raison macrumors member

    Joined:
    Nov 13, 2009
    #1
    Hi there,

    I have a website that has a bunch of small scripts, and each page loads its needed scripts. I want to modularize these scripts so it'd easy to manage all of them.
    What's the best approach to start this modularization process? Is require.js a good option? Is there anything else out there you guys could recommend?
    Also, there are no test cases in place for the current scripts. Should I start writing them in the process?

    PS: PHP is the backend language.

    Thanks!
     
  2. 960design macrumors 68020

    Joined:
    Apr 17, 2012
    Location:
    Destin, FL
    #2
    For development I build lots of js files and load each one at right before the closing <body> tag. Each file does a specific task and reports in the console if there are any try/catch fails ( they also report running conditions and whatever else I need ).

    For production, I minify all js into a single file.

    I've never used require.js.
    I use CDN for stuff like Bootstrap and JQuery and the user's browser almost certainly already has a local copy, saving a couple of milliseconds.
     
  3. raison thread starter macrumors member

    Joined:
    Nov 13, 2009
    #3
    Thanks for your reply.

    If you place all the js files into a single file, don't you have problems with collisions?

    For example, say you have 2 scripts, A and B. Both scripts do something when the DOM is ready, for example, change the background color of the page to red (A) and blue (B). If you have these scripts into a single file, this could be a problem.

    That's why I was thinking about using a loader so each page only load what it needs.

    How do you circumvent this problem?

    I also use CDN, but only for css and images. I haven't deployed my JS to the CDN yet due to cross-domain issues that need be addresses before.
     
  4. 960design macrumors 68020

    Joined:
    Apr 17, 2012
    Location:
    Destin, FL
    #4
    [​IMG]

    Sorry, could not resist. Love me some nope sandwiches.

    http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html

    I dislike just links, so please bear with a little repeating if this link dies someday.

    To avoid collisions use Anonymous Clousures... basically put your code in little autocalling functions. This isolates variables and prevents collisions with external libraries, ect.

    Research a little about design patterns; specifically module patterns. Here's a good start:
    https://addyosmani.com/resources/essentialjsdesignpatterns/book/
     
  5. raison thread starter macrumors member

    Joined:
    Nov 13, 2009
    #5
    Thanks for the links, I saved them to read them later. :)
     

Share This Page