Ashish Kasma
Ashish Kasma

Reputation: 3642

Add jquery script via script file

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>

Upvotes: 0

Views: 167

Answers (2)

Chris
Chris

Reputation: 26878

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.

Upvotes: 2

Nhu Trinh
Nhu Trinh

Reputation: 13956

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

Upvotes: 4

Related Questions