Including javascript library from HTML body

I want to include a javascript library to my HTML page from inside my HTML body. i included the following script in my body part :

<script type = "text/javascript" >
var scriptHeader = document.createElement('script');
scriptHeader.setAttribute("type","text/javascript")
scriptHeader.setAttribute("src", 'http://dygraphs.com/dygraph-combined.js' );
if (typeof scriptHeader!="undefined") {
    document.getElementsByTagName("head")[0].appendChild(scriptHeader);
    // alert( "Success!!" );
}
else {

}
</script>

Now in I call my JS as

<script type = "text/javascript">
var plot = new Dygraph( 
               // ... create new graph
</script>

With out the 'alert', this is not working. It is throwing

ReferenceError: Dygraph is not defined

I assume this is a sync issue. How can I solve this?

Answers


What about to use $.getScript ?

$.getScript("someScript.js", function () {
    // use it here
});

EDIT:

Without jQuery:

var el = document.createElement('script');
el.async = true;
el.src = 'http://jsfiddle.net/js/moo-clientcide-1.3.js?jobofferinsidebar';
el.onload = function(){
    alert('loaded');
    // use here
};

el.onerror = function(){
    alert('fail');
};

document.head.appendChild( el );

Here is fiddle


Need Your Help

append new row to old csv file python

python csv append writer

I am trying to add a new row to my old csv file. Basically, it gets updated each time I run the Python script.

Is there any way to make a JTextArea in one class respond to JButton clicks in another?

java swing user-interface action observer-pattern

I need to make the JTextField in my ChatPanel class respond to JButton clicks in my Toolbar class. Is there any way to do this that will scale well if my program gets large? I tried doing this with...