What's the Zepto equivalent of jQuery.getScript()? I need to dynamically load a JavaScript file with both libraries.
What's the Zepto equivalent of jQuery.getScript()?
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 );
}
})($)
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
;(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
.
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.
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.