HOW TO check if an external (cross-domain) CSS file is loaded using Javascript

Asked
Active3 hr before
Viewed126 times

7 Answers

usingcheckexternal
90%

Set the class name using setAttribute,Insert the link element in head tag.,appendChild the div on body.,Now getting CSS rule value using document.defaultView.getComputedStyle(divElement, null)[cssRule].

Then use this to load the css:

function loadCss(cssText, callback) {
   var style = document.createElement('style');
   style.type = 'text/css';
   if (callBack != undefined) {
      style.onload = function() {
         callBack();
      };
   }
   style.innerHTML = cssText;
   head.appendChild(style);
}

And use it like this:

loadCss(ajaxResponseText, function() {
   console.log("yaay css loaded, now i can access css defs");
})
load more v
88%

Insert the link element in head tag.,I have a function doing the following using javascript:,Create link element and set href=cssFile.,Now I have a JavaScript function which will fire the callback specified when the above style is loaded on the page:

To ensure a specific CSS file is loaded, I added a style in the end of the CSS file. For example:

#ensure - cssload - 8473649 {
   display: none
}

Now I have a JavaScript function which will fire the callback specified when the above style is loaded on the page:

var onCssLoad = function(options, callback) {
   var body = $("body");
   var div = document.createElement(constants.TAG_DIV);
   for (var key in options) {
      if (options.hasOwnProperty(key)) {
         if (key.toLowerCase() === "css") {
            continue;
         }
         div[key] = options[key];
      }
   }

   var css = options.css;
   if (css) {
      body.appendChild(div);
      var handle = -1;
      handle = window.setInterval(function() {
         var match = true;
         for (var key in css) {
            if (css.hasOwnProperty(key)) {
               match = match && utils.getStyle(div, key) === css[key];
            }
         }

         if (match === true) {
            window.clearTimeout(handle);
            body.removeChild(div);
            callback();
         }
      }, 100);
   }
}

And this is how I used the function above:

onCssLoad({
   "id": "ensure-cssload-8473649",
   css: {
      display: "none"
   }
}, function() {
   // code when you want to execute 
   // after your CSS file is loaded
});
load more v
72%

The only real solution to this problem is to CORS load your CSS in the first place. By using a CORS XMLHttpRequest to load the CSS from an external domain, and then injecting the responseText (actually responseCSS in this case) into the page via something like:,I get this error in Firebug when I try to access some CSS files hosted on external domains:,Is there a way to fix this, beside moving all the CSS files on the same domain?,After that, you can access its rules via Javascript.

I get this error in Firebug when I try to access some CSS files hosted on external domains:

Security error " code: "
1000
rules = styleSheets[i].cssRules;

The code I am using is:

$(document).ready(function() {
   $("p").live('mousedown', function getCSSRules(element) {
      element = $(this);
      var styleSheets = document.styleSheets;
      var matchedRules = [],
         rules, rule;
      for (var i = 0; i < styleSheets.length; i++) {
         rules = styleSheets[i].cssRules;
         for (var j = 0; j < rules.length; j++) {
            rule = rules[j];
            if (element.is(rule.selectorText)) {
               matchedRules.push(rule.selectorText);
            }
         }
      }
      alert(matchedRules);
   });
});
load more v
65%

The same-origin policy is a critical security mechanism that restricts how a document or script loaded by one origin can interact with a resource from another origin.,The approach described here (using the document.domain setter) is deprecated because it undermines the security protections provided by the same origin policy, and complicates the origin model in browsers, leading to interoperability problems and security bugs.,The same-origin policy controls interactions between two different origins, such as when you use XMLHttpRequest or an <img> element. These interactions are typically placed into three categories:,A page may change its own origin, with some limitations. A script can set the value of document.domain to its current domain or a superdomain of its current domain. If set to a superdomain of the current domain, the shorter superdomain is used for same-origin checks.

document.domain = "company.com";
75%

If your Matomo tracking code doesn't look like this one, you may be using the deprecated version. Older versions still work as expected and will track your visitors, but we highly recommend that you update your pages to use the most recent tracking code.,You can push to the _paq array even after the matomo.js file has been loaded and run.,To use all the features described in this page, you need to use the latest version of the tracking code. To find the tracking code for your website, follow the steps below:,The matomoAsyncInit() method will be executed once the Matomo tracker is loaded and initialized. In earlier versions you must load Matomo synchronous.

The tracking code looks as follows:

<!-- Matomo -->
<script type="text/javascript">
  var _paq = window._paq = window._paq || [];
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//{$MATOMO_URL}/";
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', {$IDSITE}]);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<!-- End Matomo Code -->
load more v
40%

Requesting a file from another domain can cause problems, due to cross-domain policy.,JSONP stands for JSON with Padding.,Requesting an external script from another domain does not have this problem.,JSONP is a method for sending JSON data without worrying about cross-domain issues.

JSONP is a method for sending JSON data without worrying about cross-domain issues.

JSONP does not use the XMLHttpRequest object.

XMLHttpRequest
load more v
22%

The SRC attribute specifies the URL of the external file that needs to be loaded. The browser reads the script file from the cache, if available, or makes an HTTP request to fetch the script.,The techniques listed here provide the benefits of external scripts without the slowdowns imposed from blocking:,External scripts pull in the JavaScript from a separate file using the SCRIPT SRC attribute:,Figure 4-1 shows the HTTP requests for the Scripts Block Downloads example.[9]

<script>
function displayMessage(msg) {
    alert(msg);
}
</script>
<script src='A.js'></script>
load more v

Other "using-check" queries related to "HOW TO check if an external (cross-domain) CSS file is loaded using Javascript"