0

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?

v-i-s-h
  • 61
  • 2
  • this is because you are adding the script element to the page after the page is rendered, thus the browser did not download the script and because of that it does not know about Dygraph – Armand Dec 09 '13 at 11:26
  • possible duplicate of [dynamic script loading synchronization](http://stackoverflow.com/questions/774752/dynamic-script-loading-synchronization) – JJJ Dec 09 '13 at 11:27

1 Answers1

1

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

Tony
  • 7,345
  • 3
  • 26
  • 34
  • The thing is I cannot use jQuery or any other JS libs. I don't have control over what's in the head part of the HTML( it's generated by my master engine, which I'm not supposed to edit ). only thing I can do is to write any script in body part of HTML. – v-i-s-h Dec 09 '13 at 11:44