0

For example I have a website with some pages like the following sample:

  • login.html
  • user-info.html
  • products.html
  • product.html

I have different scripts for these pages. So I have:

  • login.js
  • user-info.js
  • products.js
  • product.js

I can concat these files into one or import with ES6 modules and get "scripts.min.js".

However if I have in login.js something like:

document.ready(function() {
   alert('Hello, this is logic for login.js');
})

then I get this messages for all pages.

I am searching for right way to divide logic between pages. All information about JavaScript architecture I found unfortunately was about SPA.

What's right way to organize JS structure in ordinary website to make it maintainable and scalable?

3
  • 1
    Uh... just don't concat these files? Commented May 7, 2018 at 5:42
  • 1
    There is no way to prevent this apart from manual checks, maybe based on the URL of the page, or by segregating the logic in AMD modules or so. Commented May 7, 2018 at 5:43
  • 31piy, Does modules helps to execute script only for target page? Commented May 7, 2018 at 6:19

1 Answer 1

1

UPDATE: If you want some code to just execute on specific pages you could do something like this (onload):

var _tgt = window.location.href; //where are we

var _is_login = _tgt.search("login");

if (_is_login !== -1) {
  console.log("Do something in login");
}

You could use node modules to trim your code:

  • To remove comments and compress: uglify-js npm module.
  • To combine various js files you could do something like this:
    1. Read in files using (eg) npm module fs-readdir-recursive and fs
    2. Remove unwanted content with eg regex
    3. Create a new file (combined)
Sign up to request clarification or add additional context in comments.

1 Comment

Does any more beautiful way exists to do it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.