Conditionally load d3.js (if not already loaded)

983 views
Skip to first unread message

Neha Jain

unread,
Jun 20, 2012, 1:45:03 AM6/20/12
to d3...@googlegroups.com
Hello All,
I want to load d3.js only when it is not already loaded on the page. The scenario is that I have mutiple d3 charts on a single page but I do not want to duplicate the loading of d3.js each time. (Each chart comes from a different source).
To do that, I check using a simple d3 command and expect it to fail <if d3.js is not loaded>

<script type="text/javascript">
     try {
        donut = d3.layout.pie();
        d3.select("body");
        console.log("d3 loaded");
       //call chart function
    } catch(e) {
        console.log("d3 not loaded");
        loadScript("/lib/js/d3.v2.min.js"}); //loads the d3.js
    }
   </script>


But this does not seem to work as the try block does not throw an error even if d3 is not loaded.

I used to use protovis and would do the same using:

 <script type="text/javascript">
    try {
        new pv.Panel().width(500).height(200);
        // call chart function
    } catch(e) {
        loadScript("/lib/js/protovis-3.3.1.min.js"});
    }
</script>
This would work.

How to solve the problem of conditional loading in d3.js? Or better still, what d3 statement would throw an exception on trying to run it without loading the js?

jerome cukier

unread,
Jun 20, 2012, 10:10:43 AM6/20/12
to d3...@googlegroups.com
how about using typeof(d3)==="undefined" ? 

Peter Rust

unread,
Jun 20, 2012, 1:19:32 PM6/20/12
to d3...@googlegroups.com
ditto Jerome. The two typical ways to check if a global is loaded in Javascript without try/catch is:

if (typeof(d3) == 'undefined') { /* load d3 here */ }

or

if (!window.d3) { /* load d3 here */ }

-- peter

Paul Jensen

unread,
Jun 20, 2012, 2:59:46 PM6/20/12
to d3...@googlegroups.com
I had a similar problem and used head.js (http://headjs.com) to solve it. I don't know for certain if it prevents multiple calls to load d3, but worth a look anyway.
Message has been deleted

Neha Jain

unread,
Jun 21, 2012, 5:52:16 AM6/21/12
to d3...@googlegroups.com
thankyou Jerome, Peter and Paul. This works smoothly as good as the try-catch but I guess I have a slightly different problem. Will put that in another topic.
Reply all
Reply to author
Forward
0 new messages