From 1d84d180f3b1ff25783cb5bf29408b98acfb6032 Mon Sep 17 00:00:00 2001 From: Manuel Mujica Date: Wed, 24 Jan 2018 11:49:08 -0700 Subject: [PATCH] Refine logic to detect whether link exists already Chrome/Safari seem to wait until the link tag has finished loading to add it to `document.styleSheets` and that causes the slim loader to duplicate the link tag. Using `document.querySelectorAll` works fine in the three browsers Closes #64 --- slim.js | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/slim.js b/slim.js index 5c2aeaf..8dea9a7 100644 --- a/slim.js +++ b/slim.js @@ -10,15 +10,24 @@ function CssModule(address) { // timeout in seconds CssModule.waitTimeout = 60; -CssModule.prototype.linkExists = function() { - var styleSheets = document.styleSheets; +// The slim build does not resolve to URLs, so this trick is needed +// to get the url and use it to check if the link was already added +// to the head +CssModule.prototype.getLinkUrl = function() { var anchor = document.createElement("a"); anchor.href = this.address; - var href = anchor.href; + return anchor.href; +}; - for (var i = 0; i < styleSheets.length; ++i) { - if (href === styleSheets[i].href) { - return true; +CssModule.prototype.linkExists = function() { + var styleSheets = document.querySelectorAll('[rel="stylesheet"]'); + + if (styleSheets != null) { + var href = this.getLinkUrl(); + for (var i = 0; i < styleSheets.length; ++i) { + if (href === styleSheets[i].href) { + return true; + } } }