Last active
August 29, 2015 14:06
-
-
Save voxpelli/b448e9d095f655000a46 to your computer and use it in GitHub Desktop.
Promise based loading of indie-config, wrapped in an example page using that promise. More info @ http://indiewebcamp.com/indie-config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<title>Indie Configuration</title> | |
<link rel="stylesheet" href="/css/style.css" /> | |
</head> | |
<body> | |
<div class="page" id="page-wrapper"> | |
<header> | |
<h1><a href="/">Indie Configuration</a></h1> | |
<div class="subtitle">Letting the rest of the world know how you want to communicate</div> | |
</header> | |
<div id="result"></div> | |
</div> | |
<script> | |
(function(){ | |
// Lazy-create and return an indie-config load promise | |
// The promise will be resolved with a config once the indie-config has been loaded | |
var loadIndieConfig = function () { | |
// Create the Promise to return | |
var loadPromise = new Promise(function (resolve) { | |
// Parse the incoming messages | |
var parseIndieConfig = function (message) { | |
// Check if the message comes from the indieConfigFrame we added (or from some other frame) | |
if (message.source !== indieConfigFrame.contentWindow) { | |
return; | |
} | |
var indieConfig; | |
// Try to parse the config, it can be malformed | |
try { | |
indieConfig = JSON.parse(message.data); | |
} catch (e) {} | |
// We're done – remove the frame and event listener | |
window.removeEventListener('message', parseIndieConfig); | |
indieConfigFrame.parentNode.removeChild(indieConfigFrame); | |
indieConfigFrame = undefined; | |
// And resolve the promise with the loaded indie-config | |
resolve(indieConfig); | |
}; | |
// Listen for messages from the added iframe and parse those messages | |
window.addEventListener('message', parseIndieConfig); | |
// Create a hidden iframe pointing to something using the web+action: protocol | |
var indieConfigFrame = document.createElement('iframe'); | |
indieConfigFrame.src = 'web+action:load'; | |
document.getElementsByTagName('body')[0].appendChild(indieConfigFrame); | |
indieConfigFrame.style.display = 'none'; | |
}); | |
// Ensure that subsequent invocations return the same promise | |
loadIndieConfig = function () { | |
return loadPromise; | |
}; | |
return loadPromise; | |
}; | |
loadIndieConfig().then(function (loadedConfig) { | |
document.getElementById('result').textContent = JSON.stringify(loadedConfig); | |
}); | |
})(); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment