0

I have script (myscript.js) which create div and animate div in any HTML page. my script is using Jquery animation function

I am currently using following code (it's sample snippet)

<script src="jquery.js"><script>
<script src="myscript.js"><script>

But is this possible to use only following code which can automatically add JQuery library also?

<script src="myscript.js"><script>
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
Ashish Kasma
  • 3,594
  • 7
  • 26
  • 29

2 Answers2

4

Insert this on top of your myscript.js

var h=document.getElementsByTagName('head')[0];
var s=document.createElement('script');
s.type='text/javascript';
s.src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js';
h.appendChild(s);

but you will have to wait until script loaded using waitforload function

function w4l(){
    if (typeof jQuery != "function"){
        setTimeout("w4l()", 1000);
        return;
    }else{
        //Do Jquery thing
    }
}
w4l();

or just simply copy all jquery.js code file into your myscript.js, AKA merge 2 file into one

James
  • 13,571
  • 6
  • 61
  • 83
2

To make sure that the rest of myscript.js doesn't get executed before jQuery is loaded, use something like this:

function dostuff() {
    //animate elements, etc.
}
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'jquery.js';
script.onreadystatechange = dostuff;
script.onload = dostuff;
head.appendChild(script);

Note: it's a bit unclear why you wouldn't want to explicitly add the jQuery part in your head.

Chris
  • 26,544
  • 5
  • 58
  • 71
  • 1
    The only problem is that I don't think jQuery will work with myscript.js as it will load after myscript.js does. – HellaMad Sep 23 '12 at 08:48
  • @DC_ JavaScript is generically synchronous. – Chris Sep 23 '12 at 08:50
  • it means after adding following code myscript can utilize jquery function. is this right ? – Ashish Kasma Sep 23 '12 at 08:52
  • I am looking for more solution, as i am already using this code via explicit jquery inclusion. thanks i looked your edited code.... – Ashish Kasma Sep 23 '12 at 08:59
  • 3
    @Kasma What kind of benefit are you looking for with this solution? The only twos things this accomplishes is **a)** Making your code more complicated ([KISS](http://en.wikipedia.org/wiki/KISS_principle)) and **b)** Removing _one_ element from your DOM. You will still be making the same amount of requests, etc. If you really want to improve performance, just place the contents of myscript.js at the bottom of jQuery, though this is not practical in most situations. – HellaMad Sep 23 '12 at 09:04
  • thanks @Abody97,@DC_ ... although i will use jquery in main HTML .. but i learned another way.. – Ashish Kasma Sep 23 '12 at 13:10