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"></script>
<script
type="text/javascript"
src="http://mydomain/mywidget.js"></script>
</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!
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: