简体   繁体   中英

structuring javascript/jquery in a site

So I have this website where we have loads of javascript . basically they all run on top of jQuery . The site uses a layout and multiple view files. So the structure is roughly like this:

layout.php

loadHeader();
loadBody();
loadFooter();

loadHeader() will load all the required CSS loadFooter() will load all the required JS

Now loadBody() loads different PHP scripts . Most of these scripts need jQuery/Javascript to work correctly. Right now everyone is adding all the required jQuery to a file named site.js which is loaded as the last .js file in loadFooter()

This has created a BIG monolithic code structure like:

$(document).ready(function()
{
  //init this...

  //do that...

  //bind this...

  //ajax that...
});

This is growing unmanageable very quickly. In a structure like the one we have, I am not sure if the .js files can be loaded on-demand from the loadBody() , since the dependencies (jQuery, bootstrap, plugins etc) get loaded in the end. Also, does everything need to be wrapped inside document.ready like it is now?

does everything need to be wrapped inside document.ready like it is now?

If it's only some calculation in the back-end then it doesn't matter if the document is ready or not.

If you need to manipulate or fetch something from the DOM then you need it to be ready.

This has created a BIG monolithic code structure like:

The "init this do that ajax" can become quite big, like you're experimenting, but if some parts of it are suppose to server the same/similar purpose then you could put them into separate functions and to avoid a humongous file then you could add related code into separate files.

Other than that it's quite hard to avoid, just like any code. Just make sure related code is separated in unique functions and in separated files.

$(document).ready(function()
{
    init();
    doThat();
    bindThis();
    ajaxThat();
});

Is a fair separation, but perhaps you can simplify it even better.

$(document).ready(function()
{
    init();
    handleProcessInsertName();
});

Wherea you've defined the function properly (in the same file, or preferably, in another file).

function handleProcessInsertName()
{
    doThat();
    bindThis();
    ajaxThat();
}

There are many ways to refactor the code. What I often do is:

$(function() {
    setupMenu();
    setupFooter();
    initSelect2(); 
});
// and then...
var setupMenu = function() {}
var setupFooter = function() {}
var initSelect2 = function() {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM