A common practice in modern times is to compress all the JS files into one and connect them to <head> . Working with such a structure, at what point and how should variables and classes be initialized so that the memory consumption is optimal?

I will explain the issue.

Of course, we can initialize in onload all the variables we work with, but we don’t need all the variables on a specific page of the site / application: why initialize the variables associated with the submission form if we are on the main page? And if these are DOM objects, then we will not be able to initialize them, being on a page where there are none (if we, of course, do not completely generate HTML in JS). It turns out that this option is not suitable.

In javascript question : is it worth avoiding the style of writing code “function in function”? I proposed a code structure that allows you to initialize variables only when they are needed. At the time of writing the current question, the answers like "yes, apply this approach, because <justification>" or "no, such an approach should be avoided, because <justification>" did not exist, but I myself used the data without any particular problems while did not start working with ES2015-classes.

These classes cannot be used until the declaration. So how do you first write classes inside a function (to initialize them only when they are needed), and then write auxiliary ones inside the same function - a very bad tone, the question arose: how should these classes be initialized as necessary?

  • 1 - Scripts in the header now moveton. 2 - Read about modular js - ThisMan
  • four
    @ThisMan, where is the firewood about moveton? - Grundy
  • ru.wiktionary.org/wiki/… Seriously, I suppose he means that it is safer to run scripts from the end of the document so that the existing markup has already processed the browser. - 11111000000

1 answer 1

You mix different things: initialization and definition of dependencies.

The definition of dependencies is the very classes and functions that need other classes and functions. If everything is done correctly, then there is no reason to avoid creating classes and functions right away. All this, in fact, takes quite a bit of time.

Initialization (communication with DOM elements, setting event handlers, starting background scripts) should be done on demand.


Specific advice. To manage dependencies, use modules. There are libraries such as requirejs, systemjs. There are tools like browserify and webpack.

All of them allow to glue different files into one so that they are not executed immediately, but on demand.

An example of communication between two modules. AMD format (Asynchronous Module Definition, asynchronous module definition):

 //a.js define(function () { return { foo: function () { console.log("Hello, world!"); } } }); //b.js define(['a'], function (a) { return { bar: function () { a.foo(); } } }); 

CommonJS format (in the browser it will not work directly - but the tools for gluing the modules know how to handle this format):

 //a.js exports.foo = function () { console.log("Hello, world!"); } //b.js var a = require("a"); exports.bar = function () { a.foo(); } 

ES6 format is also not for the browser:

 //a.js export function foo() { console.log("Hello, world!"); } //b.js import foo from 'a'; export function bar() { foo(); } 

By initialization.

In library modules, just do not touch the DOM until you are asked. The page should somehow indicate which file to include and what function to call. In the simplest case, you can add a second script tag to the page, where the inline script will make a call to the desired function. Or you can use the attributes to specify this data (by the way, the complete absence of inline scripts will allow you to disable them through CSP, which will increase the resistance to hacking).

Any call to the DOM should occur no earlier than when calling a function or in a class constructor (the exception is reading attributes indicating which module to load for initialization). And it is very desirable that the elements of DOM were not hardcoded there - they were selected on the basis of the passed parameters.

If a piece of markup is needed by a module for its needs (for example, this is a template), it is better to put it into a separate file and load it as a module. Browserify and webpack can do this:

 var template = require("./template.html"); // содержимое файла будет, скорее всего, "подклеено" в общий бандл в виде строкового литерала. 

Well, be sure to look at the widely used frameworks. If not in terms of use, then at least how it is made. The same Angular (not to be confused with AngilarJs) has a recommended set of tools for development and assembly. In principle, no one bothers you to put Angular according to the instructions from their site, then delete it back - and use the tools :)

  • @ 11111000000 webpack itself will not help the author of the question. He needs ideas for organizing the code. So I gave as an example the framework where the organization of the code is pretty well thought out. If you have other ideas - write comments, your answer or add mine. And remove constructive criticism. - Pavel Mayorov
  • I already have my answer, I consider the comment constructive - 11111000000
  • Recommend learning tools Juzl. Studying documentation is another matter, but first of all it is patterns, secondly, specific implementations. Those. part of the answer about Angulyar is not constructive, of course, except for the advice to remove it back. - 11111000000
  • Thank you for the detailed answer! - Gleb