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

Issue with chaining Required Field and Regular Expression validators for Textbox controls

c# asp.net validation webforms

I'm trying to implement a form validation with ASP.net and I have tried every solution suggested here but the best one was on aspsnippets.com so far.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.