Search code examples
htmlweblessstylesheet

Read the contents of a link or script tag using src/href


How can I read the contents of a file using

<link href='path/to/file'/>

I understand that if one adds the attribute type="text/css" then they can be read using document.styleSheets but I have a hard time figuring out how to get the content of that element though.

I understand that lesscss.js lib uses the without an ajax get call.

From: http://lesscss.org/#using-less

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

I need to include some templates into the page, and the sooner they are loaded the better, ( vs doing it after jquery and js has loaded)

Thanks!


Solution

  • I understand what you mean with before jquery. But what do you mean with "before js".

    When you load less.js (which does NOT depend on jQuery) the browser runs less.js before jquery has been initialized. Notice that less.js requires JavaScript.

    You can read the content of such a file leveraging a XMLHttpRequest. A basis example which shows you how to do this can be found at: How to show the compiled css from a .less file in the browser?

    Regarding less.js, you can find the source of that file at: https://github.com/less/less.js/blob/master/dist/less-1.7.4.js

    I understand that if one adds the attribute type="text/css" then they can be read using document.styleSheets but I have a hard time figuring out how to get the content of that element though.

    Globally less.js uses two steps to do that:

    1. first it will built a list of paths as follows:

      //
      // Get all <link> tags with the 'rel' attribute set to "stylesheet/less"
      //
      var links = document.getElementsByTagName('link');
      
      less.sheets = [];
      
      for (var i = 0; i < links.length; i++) {
          if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
             (links[i].type.match(typePattern)))) {
              less.sheets.push(links[i]);
          }
      }
      
    2. Then reads the content of these files by using a XMLHttpRequest too. See the doXHR function at line 7720 of less-1.7.4.js.