sergiz's avatar

Multiple JS files per page

Hello.

I'm not sure how to handle the following situation using Laravel Mix/Webpack. Let's say my app has some JS code that is needed in every page (that extends layour.blade.php) and then every page has some of its own JS. Besides that I have some JS code that is shared between other JS files.

Overview:

layout.js (included in layout.blade.php)

pagea.js (included in pagea.blade.php that extends from layout.blade.php)

pageb.js (included in pageb.blade.php that extends from layout.blade.php)

common.js (some functions that are needed in pagea.js and pageb.js)

pagec.js (included in pagec.blade.php that extends from layout.blade.php, but doesn't need common,js code)

and then pageb.js and pagec.js also need the lodash module

How do I handle this in an optimal way?

0 likes
5 replies
gitwithravish's avatar
Level 16

@sergiz You are making it unnecessarily complicated. Layout.js is needed in every view, so add it to your layout view.

pagea.js,pageb.js,pagec.js will be added in dedicated page views.

Now the only question remains is for a common.js. You have two option, either add it in the layout file or manually add it to only pagea.js and pageb.js only.

If you are using build toold for example webpack, then, merge common.js to pagea.js or pageb.js OR import functionalities in those scripts from common.js (if its a module).

2 likes
sergiz's avatar

Yeah, I guess I am. I checked the size, and all JS code I have (for all pages) is less than 100KB (non-minified).

I guess the best solution is to simply combine everything in one file? But how do I then make the JS code execute only on the page it needs to?

bobbybouwmann's avatar

@sergiz The browser will execute all files you include on the web page. The only way to make this work correctly is by creating separate JS files. The question you should ask yourself is if this is worth all the trouble to load 100k less on the page.

You can use Laravel Mix to create multiple JS files. You just need to include in each file what you need per page.

mix
    .js('resources/js/app.js', 'public/js')
    .js('resources/js/pagea.js', 'public/js')
    .js('resources/js/pageb.js', 'public/js');
gitwithravish's avatar

@sergiz This way you can import only those functions that you need. You need to decide whether it is worth it to break your head around this or just simply import all files :)

resources/js/common.js

function f1() {
  //
}

function f2() {
	//
}

module.exports = {
  f1: f1,
  f2: f2
};

resources/js/pagea.js

//importing only needed function
import f1 from './common.js'

//use it wherever you want

webpack.mix.js

mix.js('resources/js/pagea/js','public/js')
1 like
sergiz's avatar

Thank you for all your inputs. I solved the problem using dynamic imports in webpack.

1 like

Please or to participate in this conversation.