Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js : Uncaught TypeError: Cannot read property 'document' of undefined

I'm having a really weird problem with d3.js initilization. In the d3.js script, at the very beginning, it tries to get var d3_document = this.document; but it pops the following error:

Uncaught TypeError: Cannot read property 'document' of undefined

when debugging, this.document returns undefined.

I'm using yo webapp to generate the project. It uses bower as package manager and gulp for the build process (that uses babel for the ES2015 features).

The funny thing is that I've tested it with xampp and it works fine!

I would appreciate some advice!Thnx!

like image 257
Carlos Araya Avatar asked Feb 22 '16 17:02

Carlos Araya


1 Answers

It sounds like something (Babel, most likely) is inserting "use strict"; at the beginning of the D3 script file or combining it into another file with "use strict" at the top. That means this at global scope (or in a function called without a specific this) is no longer a reference to the global object, it's undefined. (Whereas in "loose" mode or in a function called with no specific this value, this at global scope is a reference to the global object, which is also accessible via the global variable `window1.)

You need to remove your d3.js from the list of scripts being transformed by Babel and just include it as-is. Assuming you're using the normal d3.js file, it looks like this:

!function() {
  var d3 = {
    version: "3.5.16"
  };
  var d3_arraySlice = [].slice, d3_array = function(list) {
    return d3_arraySlice.call(list);
  };
  var d3_document = this.document;
  // ...
  // ...
  // ...lots of stuff here...
  // ...
  // ...
}();

That relies on being run in loose mode.

like image 176
T.J. Crowder Avatar answered Sep 21 '22 13:09

T.J. Crowder