问题
I've got a site which is loading all kinds of external scripts using Modernizr.load (aka YepNopeJS). One of those scripts is a small statistics script (3,5 kB uncompressed) with a very simple callback function:
Modernizr.load({
load: 'http://res.xtractor.no/x.js',
callback: function() { _pxReg(); }
});
_pxReg is simply a function defined in the x.js script. In about 50% of my pages, I receive an error message "Undefined variable: _pxReg" (Opera 12) or "'_pxReg' is undefined" (Internet Explorer 9). Firefox 15 and Chrome 22 never give errors. The error never occurs when reloading a page.
This seems to be a timing error of some sort. In the IE developer tools, the source of the x.js file is empty at the moment the error occurs. This seems to be related to the double-request "bug" in YepNope (http://yepnopejs.com/#twice), because in IE you get two references to every loaded JS file where the first one is always empty.
I would have liked to produce a complete example that triggers this error, but it seems to related to the complexity of the page. Simplified versions of the page never trigger this error.
Does anybody know anything about what could be causing this, and how I should fix it? The site address is http://www.husbanken.no/.
回答1:
The callback happens once per resource load, meaning it will execute once for n in load : ['x.js', 'y.js']
If you load the resource using yepnope.js(basically Modernizr.load with more abilities: prefixes, timeouts and more) and provide a callback, you can catch the keys in the closure and execute your function like this:
yepnope([{
load : {'x':'//x.js'},
callback : function(url, result, key){
if("x" === key && result === true) { _pxReg() };
},
complete : function(){ console.log("all done..")}
}])
Let me know if this helps :)
来源:https://stackoverflow.com/questions/12182805/yepnopejs-callback-triggered-before-tiny-js-file-is-fully-loaded