-1

I get an error in my console, which says "Firebase is not defined".

1. Seems like this "base" code haven't loaded before the other one.

EDIT cannot put the script in the header so need to do it this way

var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "https://cdn.firebase.com/v0/firebase.js";
document.head.appendChild(script);

2. So I need to delay these somehow. How would I achieve that?

var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
myDataRef.on('child_added', function(snapshot) {
var post = snapshot.val();
});

function submitPost(e) {
var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
var name = $('#field0').val();
myDataRef.push({name: name});
$('#field0').val('');
}

3. I tried to put it within $( document ).ready(function() but didn't work. Link: https://learn.jquery.com/using-jquery-core/document-ready/

bjiang
  • 6,068
  • 2
  • 22
  • 35
Hbaecklund
  • 261
  • 1
  • 4
  • 16

2 Answers2

1

Use onload method of document.createElement(), this way:

var script = document.createElement('script');
script.onload = function() {
  // put here code which depends on Firebase to be loaded...
};
script.type = "text/javascript";
script.src = "https://cdn.firebase.com/v0/firebase.js";
document.head.appendChild(script);
MarcoS
  • 17,323
  • 24
  • 96
  • 174
1

What you are looking for is onload event:

var script = document.createElement("script");
document.head.appendChild(script);

script.onload = function() {
    var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
    myDataRef.on('child_added', function(snapshot) {
        var post = snapshot.val();
    });

    function submitPost(e) {
        var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
        var name = $('#field0').val();
        myDataRef.push({name: name});
        $('#field0').val('');
    }
};
script.type = "text/javascript";
script.src = "https://cdn.firebase.com/v0/firebase.js";

Note that according to this SO thread [ Trying to fire the onload event on script tag ] the order of those operations (calling appendChild, setting src and onload) matters. Haven't check that.

Also since you are using jQuery you might want to have a look at getScript function: http://api.jquery.com/jQuery.getScript/

Community
  • 1
  • 1
freakish
  • 54,167
  • 9
  • 132
  • 169