Answer the question
In order to leave comments, you need to log in
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.pathname
determines 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
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.
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 ) {
//ваш код
}
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.
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();
})
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question