E
E
efim232016-12-12 21:45:07
JavaScript
efim23, 2016-12-12 21:45:07

Does it make sense to execute js code only on the page intended for it?

Good day!
I've been wondering about this for a long time, but I haven't been able to find a discussion on it.
To begin with, I will give an example of my implementation
Let's say we have a JS client with Webpack (we collect all the modules in one file and not only).
One of the modules, let's call it pageHandler, has a condition that window.location.pathnamedetermines which page the user is on and executes the code of the module responsible for the JS on this page.
Okay handlers, the event loop is unlikely to notice the difference, but prevent the rest of the code, perhaps it makes sense?
I ask for the most detailed answer. Thank you)

Answer the question

In order to leave comments, you need to log in

5 answer(s)
V
vjjvr, 2016-12-12
@vjjvr

If you're talking about downloading, don't.
Let the same file be everywhere.
It will be cached better this way.
And do not execute code that is not needed - by itself it is not necessary to execute such code.

I
iBird Rose, 2016-12-12
@iiiBird

if the code is not large and does not greatly increase the volume of your main js that is loaded onto the page, then simply linking the code to the block will suffice. for example like this:

if ( $('нужный div').length > 0 ) {
   //ваш код
}

and if the code is really massive and several hundred lines long, then yes - it's better to connect it separately on the page where it should be.

A
akzhan, 2016-12-13
@akzhan

No. Let everyone suffer.
PS: I hope you understand

A
Anton Khmyrov, 2016-12-13
@vivcogit

If there are few pages, then you can put the common code into a separate bundle, and for the current page, load the one that it needs.

A
Andrey Salnikov, 2017-01-28
@Shshzik

I'll make my small contribution, I hope it helps. An example from my own life. There is a site that was made up before me with the addition of all sorts of libraries, etc. jquery, jquery-ui, popups, carousels, etc.
In the end, the file became too much. We decided to downsize. I merged all these files into 1, collected using webpack. 1 meter file turned out or something. Few, but not the point. After inspecting the site, it turned out that jquery-ui is needed only for 1 (!) Page. And loaded on everyone. And so with several libraries. And I found a great solution for myself require.ensure - lazy loading. And now all the libraries that are needed only on certain pages are loaded only on them. Here.

if ( $('нужный div').length > 0 ) {
   require.ensure([], require => {
var mdl = require('твой модуль');
mdl();
})
}

This is the code I am using.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question