Download LessCSS with jQuery

I download LessCSS from Google Code with jQuery and want to access LessCSS ' Parser()with less.Parser.

I can do this LessCSS w / jQuery download by hacking the tag <link rel>into <head>; however it loads style.lesstwice. I would prefer to download style.lessand use toCSSfor dynamic insertion. This requires a challenge less.Parser.

Currently, the code below will not embed css; I think because I am not using the correct namespace for the class Parser.

How can I dynamically load LessCSS with jQuery ?


Question source code

<script type="text/javascript" id="less_hack">
    // Load LessCSS javascript
    var less_file="/style.less";
    $(function() {
        var css="";
        $.getScript("toCSS.js")
        $.getScript("http://lesscss.googlecode.com/files/less-1.3.0.min.js",function(){
          $.get(less_file,function(data){
            new(less.Parser)().parse(data,function(e,tree){
              css = tree.toCSS();
            });
          });
        });
    });
    // $('head').append('<link rel="stylesheet/less" type="text/css" href="'+less_file+'">');
</script>

I am much more fluent in Python than JavaScript; I apologize in advance if I somehow missed the basic concept of js.


Changed code after Patrick's answer

<head>
<script type="text/javascript"
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
<script type="text/javascript">
    // Load LessCSS javascript
    var less_file="http://www.mysite.local/style.less";
    $(function() {
        var css="";
        $.getScript("http://lesscss.googlecode.com/files/less-1.3.0.min.js",function(){
          $.get(less_file,function(data){
            var parser = new(less.Parser);
            parser.parse(data, function (err, tree) {
                if (err) { return console.error(err) }
                css = tree.toCSS();
                // Insert rendered css inline
                $("<style/>").html(css).appendTo("body");
            });
          });
        });
    });
</script>
</head>
+5
source share
1 answer

Update:

I think the problem was that you called Parser as a function instead of an object new(less.Parser)().

Change the code as follows:

var less_file="/style.less";
$(function() {
    var css="";
    $.getScript("http://lesscss.googlecode.com/files/less-1.3.0.min.js",function(){
      $.get(less_file,function(data){
        var parser = new(less.Parser);
        parser.parse(data, function (err, t) {
            if (err) { return console.error(err) }
            css = t.toCSS();
            $("<style/>").html(css).appendTo("body");
        });            
      });
    });
});

See the working version here: http://jsfiddle.net/E6hsC/

+4
source

All Articles