Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

javascript - Load less.js rules dynamically

I'm looking at using less.js (looks great), but our site requires that some styles be loaded dynamically after initial page load. It seems, however, that all LESS stylesheets must be loaded prior to the less.js script load. i.e. this works

<link rel="stylesheet/less" href="/static/less/style.less"/>
<script src="http://lesscss.googlecode.com/files/less-1.0.30.min.js"></script>

but it fails if the lines are swapped around, neither firefox nor chrome appear to attempt loading 'style.less' unless they are ordered correctly. The ordering requirement is noted explicitly in this tutorial.

Is there any way to load less stylesheets after initial page load?

Note that this blog describes a 'watch' feature -

which will auto-refresh the CSS whenever you save your LESS code

so it seems reasonable to expect that I could add some LESS rules after page load. Feels like I'm missing something.

Cheers,

Colin

UPDATE: code used to test behaviour described in comments (less style sheet listed after the script) -

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Simple</title>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script src="/static/js/less-1.0.31.min.js"></script> 
  <link rel="stylesheet/less" href="/static/less/style.less" id="abc123"/>
</head>
<body>
  <div id="container">
    <div>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</div>
  </div>
  <div id="#abc">Bingo</div>
</body>

<script>
console.log("refreshing styles...");
less.sheets.push(document.getElementById('abc123'));
//var lessStyle = $("<style>#abc { color: blue; }</style>").attr("id", "less:static-less-style").attr("type", 'text/less');
//$("head").append(lessStyle);
less.refresh(true);
console.log("refreshed...");
</script>
</html>

and the less stylesheet

@primary_color: green;

.rounded(@radius: 5px) {  
  -moz-border-radius: @radius;  
  -webkit-border-radius: @radius;  
  border-radius: @radius;  
}

#container {
  background: @primary_color;
  .rounded(5px);

  div {
    color: red;
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I just pushed 1.0.31 — it has a method: less.refreshStyles() which will re-compile <style> tags with type="text/less" — try it out and let me know if it works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...