Get javascript loading out of the critical path.

This commit is contained in:
Ian Gulliver
2014-06-01 15:27:43 -07:00
parent b84b733e56
commit c004d27e9d

View File

@@ -123,49 +123,59 @@ var Cosmopolite = function(
localStorage[this.messageQueueKey_] = JSON.stringify([]); localStorage[this.messageQueueKey_] = JSON.stringify([]);
} }
/** @type {Array.<string>} */ /**
var scriptURLs = [ * @type {Promise}
'/_ah/channel/jsapi' * @private
]; */
this.channelAPIPromise_ = new Promise(function(resolve, reject) {
var script = document.createElement('script');
script.src = '/_ah/channel/jsapi';
script.async = true;
script.onload = resolve;
document.body.appendChild(script);
});
if (opt_trackingID) { if (opt_trackingID) {
scriptURLs.push('https://www.google-analytics.com/analytics.js');
/** /**
* @type {string} * @type {string}
* @private * @private
*/ */
this.analyticsObjName_ = this.uuid_(); this.analyticsObjName_ = this.uuid_();
window['GoogleAnalyticsObject'] = this.analyticsObjName_; window['GoogleAnalyticsObject'] = this.analyticsObjName_;
var settings = {
'storage': 'none',
'clientId': localStorage[this.namespace_ + ':tracking_client_id']
};
var saveCallback = (function(analytics) {
localStorage[this.namespace_ + ':tracking_client_id'] =
analytics.get('clientId');
}).bind(this);
window[this.analyticsObjName_] = {
'l': 1 * new Date(),
'q': [
['create', opt_trackingID, settings],
[saveCallback],
['send', 'event', 'cosmopolite', 'load']
]
};
}
var completeCallback = (function() {
/** /**
* @type {number} * @type {function(...)}
* @private * @private
*/ */
this.numScriptsToLoad_ = scriptURLs.length; this.analyticsObj_ = window[this.analyticsObjName_];
scriptURLs.forEach(function(scriptURL) { delete window[this.analyticsObjName_];
/** @type {Node} */ }).bind(this);
window[this.analyticsObjName_] = {
'l': 1 * new Date(),
'q': [],
};
var script = document.createElement('script'); var script = document.createElement('script');
script.src = scriptURL; script.src = 'https://www.google-analytics.com/analytics.js';
script.async = true; script.async = true;
script.onload = this.onLoad_.bind(this); script.onload = completeCallback;
document.body.appendChild(script); document.body.appendChild(script);
}, this);
this.trackEvent('create', opt_trackingID, {
'storage': 'none',
'clientId': localStorage[this.namespace_ + ':tracking_client_id']
});
this.trackEvent((function(analytics) {
localStorage[this.namespace_ + ':tracking_client_id'] =
analytics.get('clientId');
}).bind(this));
this.trackeEvent('send', 'event', 'cosmopolite', 'load');
}
this.registerMessageHandlers_();
this.createChannel_();
}; };
@@ -327,10 +337,8 @@ Cosmopolite.prototype.subscribe = function(subject, opt_messages, opt_last_id) {
Cosmopolite.SubscriptionState_.ACTIVE; Cosmopolite.SubscriptionState_.ACTIVE;
} }
resolve(); resolve();
if (this.analyticsObj_) { this.trackEvent(
this.analyticsObj_(
'send', 'event', 'cosmopolite', 'subscribe', subjectString); 'send', 'event', 'cosmopolite', 'subscribe', subjectString);
}
} else { } else {
delete this.subscriptions_[subjectString]; delete this.subscriptions_[subjectString];
reject(); reject();
@@ -520,6 +528,20 @@ Cosmopolite.prototype.unpin = function(id) {
}; };
/**
* Log an event to analytics.
*
* @param {...[string]}
*/
Cosmopolite.prototype.trackEvent = function() {
if (this.analyticsObj_) {
this.analyticsObj_.apply(this, arguments);
} else if (this.analyticsObjName_) {
window[this.analyticsObjName_].q.push(arguments);
}
};
/** /**
* Generate a string identifying us to be included in log messages. * Generate a string identifying us to be included in log messages.
* *
@@ -601,32 +623,6 @@ Cosmopolite.prototype.subjectString_ = function(subject) {
}; };
/**
* Callback when a script loads.
*
* @private
*/
Cosmopolite.prototype.onLoad_ = function() {
if (--this.numScriptsToLoad_ > 0) {
return;
}
if (this.shutdown_) {
// Shutdown during startup
return;
}
if (this.analyticsObjName_) {
/**
* @type {function(...)}
* @private
*/
this.analyticsObj_ = window[this.analyticsObjName_];
delete window[this.analyticsObjName_];
}
this.registerMessageHandlers_();
this.createChannel_();
};
/** /**
* Callback for a message from another browser window * Callback for a message from another browser window
* *
@@ -917,6 +913,7 @@ Cosmopolite.prototype.onCreateChannel_ = function(data) {
return; return;
} }
this.channelAPIPromise_.then(function() {
var channel = new goog.appengine.Channel(data['token']); var channel = new goog.appengine.Channel(data['token']);
console.log(this.loggingPrefix_(), 'opening channel:', data['token']); console.log(this.loggingPrefix_(), 'opening channel:', data['token']);
this.socket_ = channel.open({ this.socket_ = channel.open({
@@ -925,6 +922,7 @@ Cosmopolite.prototype.onCreateChannel_ = function(data) {
onmessage: this.onSocketMessage_.bind(this), onmessage: this.onSocketMessage_.bind(this),
onerror: this.onSocketError_.bind(this) onerror: this.onSocketError_.bind(this)
}); });
}.bind(this));
}; };
@@ -1191,9 +1189,7 @@ Cosmopolite.prototype.onServerEvent_ = function(e) {
if (e['profile']) { if (e['profile']) {
/** @type {string} */ /** @type {string} */
this.profile_ = e['profile']; this.profile_ = e['profile'];
if (this.analyticsObj_) { this.trackEvent('set', 'userId', this.profile_);
this.analyticsObj_('set', 'userId', this.profile_);
}
this.profilePromises_.forEach(function(resolve) { this.profilePromises_.forEach(function(resolve) {
resolve(this.profile_); resolve(this.profile_);
}, this); }, this);