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

社会主义新天地 提交于 2020-01-01 03:41:03

问题


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


回答1:


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 );
    }
})($)



回答2:


;(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.




回答3:


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.



来源:https://stackoverflow.com/questions/8556465/whats-the-zepto-equivalent-of-jquery-getscript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!