views:

55

answers:

2

Disclaimer: JS novice

I have a JS widget that depends on JQuery. The widget's going to be embedded in a 3rd party site but I figure out how to avoid declaring dependency on jquery on the widget-hosting page:

3rd party's page:

<head>

<script
  type="text/javascript"
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"&gt;&lt;/script&gt;

<script
  type="text/javascript"
  src="http://mydomain/mywidget.js"&gt;&lt;/script&gt;

</head>

mywidget.js

jQuery(document).ready(function() {
     //do stuff
});

I'd rather not include jquery.js in the 3d party page but express the dependency inside mywidget.js (so i can change this dependency or add/remove others w/o having to update the widget-hosting page)

I tried adding:

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

to the top of mywidget.js but that didn't work - jquery.js did load on page load but "jQuery" was not recognized.

What did work was concatenating jquery.js and mywidget.js into a single .js file. But that seems kind of lame - is there no equivalent to?

import com.jquery.*;

thanks!

A: 

It seems that there is just a conflict regarding the jQuery variable. Are you using the noConflict mode in your script? You should do that anyways since you don't know what other frameworks the 3rd-party site is using already.

To use the jQuery noconflict mode (after jQuery is loaded):

$.noConflict();
     jQuery(document).ready(function($) {
     //your js widget here
});

A 2nd thing I would implement is checking if jQuery is already loaded. It may be that a 3rd-party site is already using it:

if (typeof jQuery == 'undefined') {
        //load jQuery here
} 
bobsoap
+2  A: 

In your script, your widget code is immediately executed after the script element is appended, but it needs to wait until the script is also download and compiled! To achieve this, use this code:

script.onload = function(){

    // ------ Your widget code here ------

}
Vincent
Thanks, Vincent - worked as advertised. Bonus question: how to extend the above to wait for multiple JS files to load? i.e. do I extend the above with:`var script2;script.onload = function(){//load 2nd library after 1st one is done loadingscript2 = document.createElement('script');script2.src = 'http://3rdparty.com/anotherlib.js';script2.type = 'text/javascript';document.getElementsByTagName('head')[0].appendChild(script2);}script2.onload = function(){//my widget code that depends on both 'script' and 'script2'} `
Nikita
Yes, exactly. But most developers say you shouldn't load more than one external script via js, because then it takes very long until the final script is executed.
Vincent