Sunday, 18 November 2018

angularjs - How can I start fetching data from the server as quickly as possible?



How can I start fetching data from the server as quickly as possible with Angular?



Currently, most of my page is populated asynchronously via a directive "fooload" placed at the root element:






/* bunch of CSS, and other resources */



Which loads data into the scope via an http GET request:



angular.module('myapp.directives').

directive('fooload', function ($http) {
return {
link: function (scope, elm, attrs) {
$http.get('/foo').success(function (data) {
scope.foo = data;
});
}
};
});



Looking at the network panel, this call is being made in the browser AFTER the requests for the resources referenced in head. How can I make the call to load /foo data as quickly as possible on page load (if possible, even before loading angular itself)?


Answer



I solved this by:



a) fetching the data even before angular loads and storing it in a global variable (I hate using a global variable, but I couldn't think of another way.)



b) manually bootstrapping angular upon load of this data (my app doesn't work at all without the data)



        var $data;

var ajax_transport = new XMLHttpRequest();

// Callback for AJAX call
function responseProcess() {
if (ajax_transport.readyState !== 4) {
return;
}
if (ajax_transport.responseText) {
$data = JSON.parse(ajax_transport.responseText);
angular.bootstrap(document, ['myApp']);

});
}
}
// Sending request
ajax_transport.open("GET", "/mydata", true);
ajax_transport.onreadystatechange = responseProcess;
ajax_transport.send();


Note: it's important to remove the tag ng-app="myapp" in your template to avoid automatic bootstrapping.




c) Using the data in my angular app:



        scope.setupSomething($data);


d) Also, to ensure that this data call begins before any other resource load, I started using a resource loader. I liked HeadJs (http://headjs.com/) the most, but the angular folks seem to like script.js (https://github.com/angular/angular-phonecat/blob/master/app/index-async.html)



Criticism or improvements welcome.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...