Merge pull request #681 from hackalyze/load-scripts-synchronously

Fix paperscript source from being executed out-of-order
This commit is contained in:
Jürg Lehni 2015-05-11 19:57:47 +02:00
commit 111d5c8f66
2 changed files with 11 additions and 5 deletions

View file

@ -450,6 +450,7 @@ Base.exports.PaperScript = (function() {
var canvasId = PaperScope.getAttribute(script, 'canvas'), var canvasId = PaperScope.getAttribute(script, 'canvas'),
canvas = document.getElementById(canvasId), canvas = document.getElementById(canvasId),
src = script.src, src = script.src,
async = PaperScope.hasAttribute(script, 'asyc'),
scopeAttribute = 'data-paper-scope'; scopeAttribute = 'data-paper-scope';
if (!canvas) if (!canvas)
throw new Error('Unable to find canvas with id "' throw new Error('Unable to find canvas with id "'
@ -462,11 +463,15 @@ Base.exports.PaperScript = (function() {
// compiling multiple scripts for the same element. // compiling multiple scripts for the same element.
canvas.setAttribute(scopeAttribute, scope._id); canvas.setAttribute(scopeAttribute, scope._id);
if (src) { if (src) {
// If we're loading from a source, request that first and then // If we're loading from a source, request the source
// run later. // synchronously to guarantee code is executed in the
// same order the script tags appear.
// If the async attribute is specified on the script element,
// request the source asynchronously and execute as soon as
// it is retreived.
Http.request('get', src, function(code) { Http.request('get', src, function(code) {
execute(code, scope, src); execute(code, scope, src);
}); }, async);
} else { } else {
// We can simply get the code form the script tag. // We can simply get the code form the script tag.
execute(script.innerHTML, scope, script.baseURI); execute(script.innerHTML, scope, script.baseURI);

View file

@ -11,11 +11,12 @@
*/ */
var Http = { var Http = {
request: function(method, url, callback) { request: function(method, url, callback, async) {
// Code borrowed from Coffee Script and extended: // Code borrowed from Coffee Script and extended:
async = (async === undefined) ? true : async;
var xhr = new (window.ActiveXObject || XMLHttpRequest)( var xhr = new (window.ActiveXObject || XMLHttpRequest)(
'Microsoft.XMLHTTP'); 'Microsoft.XMLHTTP');
xhr.open(method.toUpperCase(), url, true); xhr.open(method.toUpperCase(), url, async);
if ('overrideMimeType' in xhr) if ('overrideMimeType' in xhr)
xhr.overrideMimeType('text/plain'); xhr.overrideMimeType('text/plain');
xhr.onreadystatechange = function() { xhr.onreadystatechange = function() {