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>
1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

6 Comments

The only problem is that I don't think jQuery will work with myscript.js as it will load after myscript.js does.
@DC_ JavaScript is generically synchronous.
it means after adding following code myscript can utilize jquery function. is this right ?
I am looking for more solution, as i am already using this code via explicit jquery inclusion. thanks i looked your edited code....
@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) 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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.