What's the Zepto equivalent of jQuery.getScript()?
Asked Answered
H

3

3

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

Harmsworth answered 19/12, 2011 at 2:10 Comment(0)
U
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 );
    }
})($)
Unkennel answered 11/1, 2012 at 1:19 Comment(3)
It wouldn't be on fn. Also, since you're writing a plugin you could really simplify by using Zepto features.Alfilaria
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).Diatom
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.Diatom
H
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.

Handsome answered 18/7, 2012 at 16:17 Comment(0)
C
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.

Cryolite answered 30/4, 2012 at 14:12 Comment(1)
A limitation to this approach is that you can't do cross domain requests. Third party scripts would fail.Alfilaria

© 2022 - 2024 — McMap. All rights reserved.