tags:

views:

30

answers:

1

just for fun...

Is it possible to have a .js file that loads jquery from a remote site and then utalizes jquery inside the .js file...

so say site: www.sitea.com... doesn't use jquery. but they find this awesome script on site b that they want to use in their page... so they do a:

<script src="http://siteb.com/cool-script-location/cool-script.js" type="text/javascript" />

now... cool script uses lots of jquery... but since site a doesn't use jquery... could i do something like this in cool-script.js:

document.writeln('<script src="http://siteb.com/jquery-location/jquery-v.v.v.min.js type="text/javascript"><script');
document.writeln('<div class="test">test</div>');

$(document).ready(function() {
    $('.test').click(function() {
         <!-- cool stuff goes here -->
    });
})

This obviously doesn't work in practice or i wouldnt be asking.

A: 

It would probably be best if you simply checked for the existence of the jQuery object first and if it didn't exist, either threw an error or displayed an alert to tell the webmaster they need jQuery version 1.x.x for the script to work. Also, on the page where they can download your script, you should make it very obvious that your script is dependent on jQuery.

There are multiple reasons for this, the biggest been that developers don't like it when scripts use resources without their knowledge, and also because loading external javascript via javascript is notoriously unreliable.

Andrew Dunn
/agreed ... but im just wondering if it is possible/plausible. thats an option as a part of documentation telling them hey... you need to put this other script line in too when you use my script (i would just link them back to my version of jquery so they don't have to deal with the hassle of installing/placing/locating...)
Patrick
Hmm, "... also because loading external javascript via javascript is notoriously unreliable." Not true anymore :)
Henrik P. Hessel
There's no way to tell when the file has loaded in some browsers, and there is definitely no way to check if the file hasn't loaded.
Andrew Dunn
yeah i think thats what happens in my example up top... jquery doesnt load entirely so the document ready fails.
Patrick