A big concern related to front end performance is the burden brought by javascript includes, which tend to be big in size. Fortunately there are techniques and best practices to minimize this issue. Loading javascript files (and why not CSS files…) during navigation can be a very good idea.
Laravel Framework has a class to manage assets that allows you, among other things, to load Javascript and CSS files only when needed. All you have to do is use asset containers. Add a new file to a container and it (the file) will be loaded when the route is called and the action is executed. Let’s take a look how it works from within a controller.
Let’s assume we have an asset container being registered and its assets being loaded in the layout file (layout.blade.php):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | < ?php // Register the files Asset::container('custom')->add('CustomJS', 'js/custom.js'); Asset::container('custom')->add('CustomCSS', 'css/custom.css'); ?> < !doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Title</title> <!--dump assets to HTML--> {{ Asset::container('custom')->styles() }} {{ Asset::container('custom')->scripts() }} </head> <body> ... </body></html> |
Now we have a javascript with instructions related to products only. We create a filter before in the controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Product_Controller extends Base_Controller { function __construct() { parent::__contruct(); // Aplicar o filtro apenas nestas actions $this->filter('before', 'addAssetsToProducts')->only( array('new', 'get') ); } public function action_new() { ... } |
And in the routes.php we add the filter behavior:
1 2 3 4 | Route::filter('addAssetsToProducts', function() { Asset::container("custom")->add("products", "js/products.js");}); |
When both actions new or get are executed, the file js/product.js (in this case stored in /public/js) will be inserted in our layout file and only for those actions.
Best!
Ved


