can't access p5 constructor after including p5.js by "reading it into the page"

I want to create my own instances of the p5 "class". If I go to https://p5js.org/reference/ , open the JS console and type p5, I get the 3-argument function. But if I include p5.min.js into my own page, open the JS console, and type p5, I get an undefined variable error.

I'm very likely missing something simple...

Answers

  • Okay I tried the empty-example bundled with p5 and it works. So I guess I need to be more specific here...

    I'm actually trying to include p5.js into a Jupyter notebook.

    I'm using the following Julia code to do that:

    HTML("""<script language="javascript" type="text/javascript">"""*readstring("libraries/p5.js")*"""</script>""")

    It basically inserts the HTML snippet <script ...> contents of p5.js </script> into the page. It's only in this case that I can't access the p5 function. I tried inserting <script ...> contents of p5.js; alert('it works')</script> just to make sure the JavaScript does get inserted, and sure enough I do get the alert box.

    This is the only way one can include external libraries into Jupyter notebooks I think. Apart from including <script src="..."></script> where src points to a publicly hosted file. Which I did try, and the problem still persists.

    I'll be very happy to help anyone set up a Jupyter notebook with Julia if you want to help debug this. juliabox.com has done most of the work for us.

  • edited November 2016
    • AFAIK, the "p5.js" file is a collection of "browserified" modules that auto unpacks once executed.
    • Dunno much how that module tech works. But in its early times it was much simpler and direct.
    • Regardless, variable p5, which points to the library's constructor function, should be available after loaded.
    • An example for it: <script src=http://p5js.org/assets/js/p5.min.js></script>;
    • Then we can append any class to p5: p5.MyClass = class {}.
    • Also methods & properties directly to its prototype:
    p5.prototype.hello = name => console.log(`Hello, ${name}!`) 
    p5.prototype.E = Math.E
  • edited November 2016

    Regardless, variable p5, which points to the library's constructor function, should be available after loaded.

    This is not quite working in my case.

    I found a minimal way to reproduce the problem I'm trying to solve:

    1. create a page with empty <head> and <body> tags
    2. open it in the browser
    3. now open JS console and type in document.body.innerHTML = '<script src="http://p5js.org/assets/js/p5.min.js"></script>';
    4. type p5 to try and access the p5 constructor. (it doesn't work...)
  • edited November 2016

    http://StackOverflow.com/a/19737116

    ( () => {
      const script = document.createElement('script');
      script.src = 'https://p5js.org/assets/js/p5.min.js';
      document.querySelector('head').appendChild(script);
    } )();
    
Sign In or Register to comment.