0

I have a very simple HTML file in which I want to draw SVGs based on data I retrieve by an AJAX-call.

Should I wait until the document is fully loaded by encapsulating my code in a document.onload = function() { ... } block, or can I be sure that the document is already fully loaded when my JS code executes, since my JS code is loaded at the end of the HTML file?

The HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <link href="styles.css" rel="stylesheet">
</head>
<body>
    <svg id="first"></svg>
    <svg id="second"></svg>

    <script src="d3.v3.min.js"></script>
    <script src="myscript.js"></script>
</body>
</html>

The myscript.js code:

d3.json('data.json', function (data) {
    var svgs = d3.selectAll('svg');
    // do some fancy stuff with data and svgs
});
zabbarob
  • 1,080
  • 2
  • 11
  • 23

5 Answers5

1

You don't need and you should not add your call of d3.json on the window onload event since you're script is include at the end of your file, plus it's an ajax call.

Dimitri
  • 304
  • 3
  • 16
1

I am not quite sure if your svg is inline or not. It is quite common to run js scripts immediately at the end of file. At this point the DOM is loaded and you can interact with it. Waiting for the onload event means waiting for resources like images or css files you don't need to run your script.

ffraenz
  • 715
  • 2
  • 9
  • 31
1

You can use firebug from Firefox, it will give you the web execution sequence; accordingly you will know for sure if the document is loaded or not. Check this post: Load and execution sequence of a web page?

Community
  • 1
  • 1
0

With the way you have your code set up it probably doesn't matter if you wait for the onload event or not. However explicitly waiting for the onload event is the safer way, it can prevent issues in the future, if you change the order of your scripts for example.

Also you might want to use window.onload instead. See here.

Community
  • 1
  • 1
shortspider
  • 957
  • 13
  • 29
  • it's safier ? if it's an external script that will be loaded with just this only functionnality, loading after dom's ready will add some loading time (even insignificant) while it isn't needed, writing short is nice also – Dimitri Mar 16 '14 at 01:04
0

D3 has an awesome queueing system that makes JSON easier to deal with.

You can see it in action here: http://giscollective.org/d3-queue-js/

queue()
.defer(d3.json, 'states.json') // topojson polygons
.defer(d3.json, 'cities.json') // geojson points
.await(makeMyMap); // function that uses files

It'll wait till those files are ready and call your mapping operations. It'll also set up the json files as easy to read objects that you can parse through.

I currently use it on http://primarycolors.net and it makes everything easier to digest.