Skip to content

Instantly share code, notes, and snippets.

@stonehippo
Created April 5, 2012 18:08
Show Gist options
  • Save stonehippo/2312910 to your computer and use it in GitHub Desktop.
Save stonehippo/2312910 to your computer and use it in GitHub Desktop.
Invoking an inline Javascript that has a dependency on an deferred external lib
// If defer is working, this won't execute until the page has loaded
console.log('starting external...');
// Put in a something that takes some time, to simulate a large library load
for (var really_big_number = 10000000;really_big_number--;) {
really_big_number;
}
External = {
'wow': function() {
console.log('Wowsers!');
}
};
<!--
This example should work just about everywhere. In browsers that support the
HTML5 defer attribute on external scripts, the console logging should
indicate that the external script has started after the inline console log.
When defer is not supported, the external script will still block normally, the console logging will be in the same order as the script tags inserted, and
things proceed as normal.
This version has a dependency on jQuery, since it relies on .ready() to delay the loading of the inline script in #app.
-->
<!DOCTYPE html>
<html>
<head>
<script>
// Patch console for older IE tests
if (typeof console == 'undefined') {
console = {
log: function(string) {
alert(string);
}
}
}
</script>
<!-- Using an older jQuery, since that's what the customer is using -->
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<!-- This is the external library; it should log() when it starts up. If defer is working, this will happen AFTER the next block does it's thing -->
<script src="external.js" defer></script>
<script>
// If defer is working, this will execute immediately, before external tells us it's starting up
console.log('I am not deferred!')
</script>
</head>
<body>
<div id="app">
<!-- This represents the call to an external library that may not have been loaded yet, such as SWFObject -->
<script>
$(function() {
External.wow();
});
</script>
</div>
</body>
</html>
@stonehippo
Copy link
Author

@xxXWarMachineRoXxx it's been a while since I wrote this, but I believe was simulating an exported object that wraps an external library. I could have just called the function directly, of course, but typically an external library won't just inject methods into the global namespace.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment