I am creating a few web pages that use the same large set of data, and it takes a few seconds to load and be processed. So it only has to load & process once, I put the loading in an external .js script, and assign the resulting array to a variable that I then could use in the other pages that reference that script.
Let's call the external script that loads the data external.js and one file that uses the data index.html. index.html has script tags with src="external.js"
followed by script tags containing page-specific javascript.
How can I ensure that the index.html script waits for external.js to finish, or at least waits for the data portion to finish? I tried enclosing the code in $(function() { ... });
which is supposed to wait until the page loads, but it didn't work. I can see via console.log
that it executes index.html before it finishes external.js.
Is there another strategy I can try to ensure the external.js is completely done before the javascript in index is executed?
Added info:
The external.js is kinda long and I'd rather not post it all, just the relevant parts. In index.html and the other pages to come, I will do a lot of stuff with the data so I want it as small as possible.
External.js uses d3's json() function (here is the latest incarnation):
json = [];
var loadJson = function() {
d3.json("data/file.json", function(error, json) {
// above file is an array of about 40,000 objects, ~36MB.
json = json.filter(function(d) { .. };
// above filter keep only the objects with certain properties.
// then I drop the properties I don't care about to reduce the size of the data
var tempdata = [];
json.forEach(function(d, i) {
tempdata[i] = {
"property1thatIwant":d.property1thatIwant,
// etc.
};
json = tempdata;
console.log(json);
(Imagine all the closing brackets and stuff.)
Then in index, I want to be able to use json as a regular array of objects that I can different things with on each of my pages, but it wasn't letting me. All I'm doing right now in that file is console.log(json). That produces []
in the console, after which I get the correct data for json.
This is not an ajax question. It has nothing to do with ajax.