From 9a4fc2e7ea8baa79d7cfd11481d6932e462df4c6 Mon Sep 17 00:00:00 2001 From: Dmitry Lakhno Date: Mon, 25 Aug 2014 22:02:29 +0700 Subject: [PATCH] Load scripts synchronously External scripts were being asynchronously loaded as part of the new page being loaded. This could break inlined scripts that depended on such scripts. See original https://github.com/dieulot/instantclick/issues/85 for details --- bower.json | 2 +- trueinstantclick.js | 56 +++++++++++++++++++++++++++++---------------- 2 files changed, 37 insertions(+), 21 deletions(-) diff --git a/bower.json b/bower.json index 448adad..faa15f9 100644 --- a/bower.json +++ b/bower.json @@ -1,7 +1,7 @@ { "name": "trueinstantclick", "description": "TrueInstantClick makes following links in your website instant.", - "version": "4.0.1", + "version": "4.0.2", "main": [ "./trueinstantclick.js" ], diff --git a/trueinstantclick.js b/trueinstantclick.js index b21c3d0..741be89 100644 --- a/trueinstantclick.js +++ b/trueinstantclick.js @@ -174,6 +174,41 @@ var InstantClick = function(document, location) { ////////// MAIN FUNCTIONS ////////// + function syncload(scripts, i) { + var script, + copy, + parentNode, + nextSibling; + if (i < scripts.length) { + script = scripts[i]; + if (script.hasAttribute('data-no-instant')) { + syncload(scripts, i + 1); + return; + } + copy = document.createElement('script'); + if (script.src) { + copy.src = script.src; + } + if (script.innerHTML) { + copy.innerHTML = script.innerHTML; + } + parentNode = script.parentNode; + nextSibling = script.nextSibling; + parentNode.removeChild(script); + parentNode.insertBefore(copy, nextSibling); + // real browsers: + copy.onload = function() { + syncload(scripts, i + 1); + }; + // internet explorer: + copy.onreadystatechange = function() { + if (this.readyState == 'complete') { + syncload(scripts, i + 1); + } + } + } + } + function instantanize(isInitializing) { var as = document.getElementsByTagName('a'), a, @@ -194,26 +229,7 @@ var InstantClick = function(document, location) { a.addEventListener('click', click); } if (!isInitializing) { - var scripts = document.body.getElementsByTagName('script'), - script, - copy, - parentNode, - nextSibling; - - for (i = 0, j = scripts.length; i < j; i++) { - script = scripts[i]; - copy = document.createElement('script'); - if (script.src) { - copy.src = script.src; - } - if (script.innerHTML) { - copy.innerHTML = script.innerHTML; - } - parentNode = script.parentNode; - nextSibling = script.nextSibling; - parentNode.removeChild(script); - parentNode.insertBefore(copy, nextSibling); - } + syncload(document.body.getElementsByTagName('script'), 0); } }