3

What's the Zepto equivalent of jQuery.getScript()? I need to dynamically load a JavaScript file with both libraries.

DataZombies
  • 416
  • 6
  • 19

3 Answers3

7

This works appended to zepto.js!

;(function ($) { 
    $.getScript = function(src, func) {
        var script = document.createElement('script');
        script.async = "async";
        script.src = src;
        if (func) {
           script.onload = func;
        }
        document.getElementsByTagName("head")[0].appendChild( script );
    }
})($)
Luke Stanley
  • 1,274
  • 1
  • 16
  • 32
Kris Erickson
  • 33,454
  • 26
  • 120
  • 175
  • It wouldn't be on fn. Also, since you're writing a plugin you could really simplify by using Zepto features. – Brian Nickel Jul 02 '12 at 06:12
  • Theoretically, avoiding using $() for appending the element or setting attributes etc, should be faster and may save memory - both can be important when loading quickly. So I went with this, with a few modifications I've added (now in the edit review). – Luke Stanley Nov 02 '12 at 13:06
  • I don't know or need the async parameter so I just commented that out. If loading via the web vs. filesystem, I'd look into it for speed improvements. – Luke Stanley Nov 02 '12 at 13:08
3
;(function($){

    $.getScript = function (url, success, error) {
        var script = document.createElement("script"),
            $script = $(script);
        script.src = url;

        $("head").append(script);
        $script.bind("load", success);
        $script.bind("error", error);
    };

})(Zepto);

This is partly ripped from Zepto.ajaxJSONP.

Alex Ciminian
  • 11,398
  • 15
  • 60
  • 94
Torsten Walter
  • 5,614
  • 23
  • 26
0

I was looking for the same thing, I found that the standard $.ajax call will eval responses when the dataType === "script". I implemented it as a Zepto plugin like so:

(function ($) {
    var getScript = function (url, callback, options) {
            var settings  = $.extend({
                'url': url,
                'success' : callback || function () {},
                'dataType' : 'script'
            }, options || {});
            $.ajax(settings);
        };

    $.getScript = getScript;
}($ || Zepto));

It should work with the same syntax as the jQuery version except I added the options (3rd) parameter to allow passing of any arbitrary options to the ajax request.

Brenton Alker
  • 8,947
  • 3
  • 36
  • 37