问题
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