If the scripts are loaded in the normal, synchronous way, then just make sure that your <script>
include appears after the library scripts in the document's <head>
. If, on the other hand, those scripts are loading objects asynchronously (as seems to be the case), then create something like this:
function whenAvailable(name, callback) {
var interval = 10; // ms
window.setTimeout(function() {
if (window[name]) {
callback(window[name]);
} else {
whenAvailable(name, callback);
}
}, interval);
}
And use it like this:
whenAvailable("twttr", function(t) {
// do something
});
The function given in the second argument to whenAvailable
will not execute until twttr
is defined on the global window
object. You can do the same thing for FB
.
Important note: Those libraries probably also provide some built-in way to execute code after they have loaded. You should look for such hooks in their respective documentation.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…