Creating function for head.js gives pretty wild errors in different browsers
I'm building a function for head.js ( http://headjs.com) that will load scripts into it in much the same way as the jQuewy ( http://jquewy.com) library does. However, I'm getting some pretty crazy errors with different browsers. The desired result is to get an alert with the version of jQuery loaded:
(function() {
head.js(
jquewy_get("","jquery","ui")
);
head.ready(function(){
alert($.fn.jquery);
});
//Takes arguments and sets them so that it
//loads the urls in headjs
function jquewy_get(){
var ret = new Array();
var arg = arguments[0];
var rand = Math.floor(Math.random()*999*999);
for (var i = 1; i < arguments.length; i++){
var arg = arguments[i];
ret[i] = 'hxxp://jquewy.com/dev/headjs/?name='+arg+'&rand='+rand;
}
return ret;
}
})();
In Firefox, I get:
$ is undefined on line 39
But even weirder, the script tag is loaded (<script type="text/javascript" src="http://jquewy.com/dev/headjs/?name=ui&rand=717786"></script>
), but Firebug says that it has:
Failed to load source for: hxxp://jquewy.com/dev/headjs/?name=ui&rand=717786
Which obviously resolves fine. In Chromium it doesn't even load the script tags, and I haven't bothered to look at any other browsers yet because if it doesn't work in those two then chances are it won't work anywhere else.
You can take a look at the source here: http://jquewy.com/dev/static/headjs/test/
Edit: for those wanting to know the point of this, the point is so that you don't need to remember urls - I'm porting another service I've built called jQuewy, which allows for fast prototyping by loading libraries based on their name. My service will automatically fetch the latest sources and embed them in the page automatically. head.js is another script that does a similar thing (but is much more popular), so I want to make my service compatible with it, so that end users can choose how they load their scripts.
Edit #2: Hardcoding in my links seems to create the same errors. My server uses redirects to point to the right scripts. Is this behaviou开发者_如何学运维r normal, and is there a workaround that will be browser independent?
An error occurs due to the fact that the $ alias for jQuery is not set. Script loaded normally. You can check it by calling
alert(jQuery('#nav').html());
for example. It works. Thus you need to set alias yourself. For example:
window.$ = jQuery;
alert($('#nav').html());
no error as you can see.
BTW, since $ alias can be set any library, you must provide a mechanism for conflict resolution. As is done in jQuery.noConflict().
精彩评论