1

I'm working on a javascript widget (with jQuery) that others can embed on their webpage doing something like this:

<html>
<head><script type='text/javascript' src="http://example.com/widget.js"></script></head>
<body>
<script type='text/javascript' id="widgetAnchor">
showWidget(1,2);
</script>
</body>
</html>

My widget needs to load several items:

  1. jQuery
  2. jQueryUI
  3. widget.css
  4. data from my server (using jQuery.getJSON)
  5. an image from my server (when the img tag is added to the document)

I'm currently loading 2, 3, and 4 using a chaining technique, which is slow. Since the three are independent, I would like to load these simultaneously. Could I do this by not using a callback function, and instead using jQuery.load() to signal that all of these are present and I can proceed with rendering the widget?

Also, is there way to load the image in parallel with 2, 3, and 4? Would it make sense to immediately add the img tag to the widget and then later moving it to the right place when I am rendering the widget?

new name
  • 15,861
  • 19
  • 68
  • 114

1 Answers1

1

If you're using preset versions of these libraries, I'd suggest concatenating and minifying them. For bonus points, bootstrap the file using embedded data that the user would have fetched from the server using getJSON().

That way, there's only one file to serve for Javascript, but CSS and the image would need to be loaded separately.

Unless of course, you're not against using something like embedding the following:

var CSSText = '...';
$('head').append('<style>' + CSSText + '</style>');

And maybe even use a Data URI encoded image:

var dataURI = '...':
var widgetImage = new Image;
widgetImage.src = dataURI;
$('#my-widget').css('background-image', 'url(' + dataURI + ')';

That way you can reduce everything to a single request to your server with no additional requests necessary for initial display.

Klemen Slavič
  • 19,661
  • 3
  • 34
  • 43
  • Thanks, great answer. I had been using Google CDN to get jQuery, to reduce some of the load on my own server, but combining them all into a single js file on my server seems to be a much better solution. – new name Jan 08 '12 at 05:36