简体   繁体   中英

application.js is large - divide it up?

My application.js file has the following:

//= require jquery
//= require jquery_ujs
//= require jquery.ui.all
//= require bootstrap
//= require_tree .

It includes another 18 js files in my javascript folder tree. The file is getting pretty large.

I use multiple cloudfront instances to serve my other assets (ie images), and have noticed that application.js can take up to a second to load (even after being gzipped).

How could I split up application.js (and application.css for that matter) into 4-5 chunks so that it can load faster? Is this possible or even the right thing to do?

It makes no difference. If you split them up then you still have to load the exact same amount of JS.

Instead maybe look at scripts that are only needed on particular pages and extract it away and have it load only on the relevant pages.

You could remove all the jquery stuff and load them individually. Trade off is two HTTP requests (or more) instead of the single one for application, but it might be worth it.

Or you could load jquery from google's CDN and if the user has that cached already save more time.

Often JavaScript is written to interact with specific elements on a page; if so, the browser will evaluate the JavaScript on every page but only activate it if the appropriate page element is present. The JavaScript you need for that page can be part of the site-wide application.js script or it can be included on the page with a javascript_include_tag statement in the view template or application layout.

JavaScript execution can be determined by

  • the presence of unique elements on the page or
  • attributes in the HTML body tag.

A more organized approach is to test for attributes in the HTML body tag:

  • Set class or id attributes on your page's body element.
  • Use functions in your JavaScript that parse those classes or ids and call the appropriate functions.

First you must modify the application layout. Replace the <body> statement in the app/views/layouts/application.html.erb file:

<body class="<%= params[:controller] %>">

Assuming a page is generated by a Projects controller, the rendered page will include:

<body class="projects">

Use this condition in your JavaScript code:

$('document').ready(function() {
  if ($('body.projects').length) {
    console.log("Page generated by the projects controller.");
  }
});

(...from RailsAppsProject, "Unholy Rails: Adding Javascript to Rails" . Read it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM