Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading LessCSS with jQuery

I am loading LessCSS from Google Code with jQuery, and want to access LessCSS' Parser() object by using less.Parser.

I can make this load LessCSS w/ jQuery by hacking in a <link rel> tag in <head>; however that loads style.less twice. I would rather load style.less and use toCSS to insert it dynamically. Doing so seems to require calling less.Parser.

Currently the code below will not insert css; I think it's because I am not using the right namespace for the Parser class.

How can I dynamically load LessCSS with jQuery?


Original code for question

<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; apologies in advance if I have somehow missed a basic js concept.


Modified 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>
like image 478
Mike Pennington Avatar asked Oct 08 '22 04:10

Mike Pennington


1 Answers

Update:

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

Modify your code to this:

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 a working version here: http://jsfiddle.net/E6hsC/

like image 71
pat34515 Avatar answered Oct 13 '22 09:10

pat34515