3
votes

I'm using requirejs to build my Backbone project. It's all working well and I'm able to use the optimizer to compile all the js modules and templates into a single main.js file. The problem is that main.js is about 1.5 meg. At work, this is fine as our internet connection is quick, but I'm noticing that with some slower connections, require.js times out before main.js is able to load.

Is there any way around this that doesn't make me alter the waitSeconds timeout?

For example is there a way to break up the main.js file into multiple pieces, or to force require to wait until there's an error produced when loading main.js?

1

1 Answers

4
votes

I think you dont need all the 1.5mb to show the user the inital app. So you can require some parts with conditions in your code. So instead of:

define(['module1','module2','module3','module4'], function(m1, m2, m3, m4){
   if(m1.someCondition){
    m2.start()
  }else{
    m3.start()  
  }
})

You can load parts of the app using require:

define(['module1'], function(m1){
  m1.start();
  if(m1.someCondition){
    var name = 'module2'
    m2 = require(name)
    m2.start()
  }else{
    var name = 'module3'
    m3 = require(name)  
    m3.start()  
  }
})

Note that the optimizer will only ignore the modules when the passed name is not a string

From the docs:

The optimizer will only combine modules that are specified in arrays of string literals that are passed to top-level require and define calls, or the require('name') string literal calls in a simplified CommonJS wrapping. So, it will not find modules that are loaded via a variable name:

var mods = someCondition ? ['a', 'b'] : ['c', 'd'];
> require(mods);