Search code examples
javascriptjqueryhtmlappendappendchild

How to append child load first in Javascript?


I want add js file dynamically at the first of <head> tag. my file is given below

Examble link : Link

Code

<!DOCTYPE html>
<html>
<head>
      <script type="text/javascript">
        function load() {
        var doc = document;
        var url = "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js";
        var id =  1;
        var script = doc.createElement("script");
        script.type = "text/javascript";
        script.src = url;
        script.id = id;
        //alert(script);
        var head = doc.getElementsByTagName( "head" )[ 0 ].appendChild( script );

        }
         window.onload = load;

        </script>   
<title>Nathan</title>
<style>
table{
    width:200px;
    margin:0 auto;
    background-color:#eee;
    text-align:center;
    cursor:pointer;
}
th{
    background-color:#333;
    color:#FFF;
}
div#lyrics{
    width:200px;
    height:400px;
    background-color:#7C8698;
    position:absolute;
    left:500px;
    padding:10px;

}
</style>
<script type="text/javascript">

$(document).ready(function(){

    $("div#lyrics").hide();

    $("#songlist tr").mouseover(function(){
        $(this).css("background-color","#ccc");
        $("#lyrics",this).show();
    }).mouseout(function(){
        $(this).css("background-color","#eee");
        $("#lyrics",this).hide();
    });

});
</script>

</head>

<body>
    <table id="songlist">
        <th>Songs</th>
        <tr><td>song1<div id="lyrics">la la la song1</div></td></tr>
        <tr><td>song2<div id="lyrics">doo doo doo song2</div></td></tr>
        <tr><td>song3<div id="lyrics">fee fi fo fum song3</div></td></tr>
        <tr><td>song4<div id="lyrics">hmm hmmm song 4</div></td></tr>
        <tr><td>song5<div id="lyrics">ma ma mi mi song5</div></td></tr>
        </tr>
    </table>
</body>
</html>

Dynamic script adding successfully but its adding last of head tag. so my jquery function not working. so please advise me how can i load my dynamic script on first in head tag


Solution

  • Adding jQuery first in the head section will still not work, cause the request to the source file will come async, why dont you add jQuery like a normal script tag:

    <head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
      <script>/*jQuery dependent code*/</script>
      ...
    

    If you will/have to use the async loading you will have to wait for the script to be loaded before adding any jQuery dependent code:

    <script> // Pseudo code: (Take a look at http://www.ejeliot.com/blog/109 for more complex solution)
      var script = document.createElement('script');
      script.onload = init;
      script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js';
      document.body.appendChild(script);
    </script>
    
    <script>
      function init() { /* now jQuery is loaded */ }
    </script>