js-of-ocamlocsigen

Calling an external Js lib from Eliom client code


I am trying Eliom right now, to see what I can do with it. I want to call an external javascript library from my eliom client code. The example code I'm trying is the following:

[%%client
  let three_lib = Js.Unsafe.js_expr "THREE" in

  let scene2 = Js.Unsafe.new_obj three_lib##.Scene [||] in

  let init () =
    (Firebug.console##log three_lib : unit);
    (Dom_html.window##alert (Js.string "scene2 created") : unit) in

  init()
]

Equivalent to the simple javascript:

var scene2 = new THREE.Scene();
function init () {
  console.log(THREE);
  window.alert("scene2 created");
}
init();

A simple call to Three.js from OCaml code. Now, I'm not 100% sure of the syntax yet, but what I observe is that THREE is undefined because this code is executed before loading Three.js.

How do I either: 1) include js files before the one generated by js_of_ocaml; or 2) include Three.js in the generated js file; or 3) other option?

Currently, the page is generated this way:

Eliom_tools.F.html
  ~title:"Main Page"
  ~js:[["lib";"three.min.js"]]
  Html5.D.(body .... )

Thank you in advance


Solution

  • I found the origin of my problem and the solution.

    I discovered that the problem was in the fact that by default, js scripts are included with the "defer" attribute (and thus interpreted after the page is fully loaded).

    After much probing, I found a way to generate the page with a script interpreted before OCaml-generated js, it must be "manually" included:

    Eliom_tools.F.html
      ~title:"Main Page"
      ~other_head:[Html5.D.script ~a:[a_src 
        (Xml.uri_of_string "lib/three.min.js")] (pcdata "")]
      Html5.D.(body .... )