Skip to content Skip to sidebar Skip to footer

Javascript Replace "variables" In Html Code Faster

I'm building a multi-language single page website with javascript and the new html template-tag and would like to use own variables like {{txt.welcome}} in html which should be rep

Solution 1:

The biggest issue, I think, is that you are not just running a regex, but also running a replace over the entire HTML multiple times. And you are setting the actual DOM HTML multiple times rather than manipulating a string until you get the result, and then setting the HTML once. I would strongly recommend using a library like Handlebars.js, but if you want to do it yourself, a very quick implementation would be something like:

var translations = { 
    heading: { 
        hello: "hello" 
    }, 
    txt: { 
        welcome: "welcome" 
    }, 
    image: { 
        description: "this is a test" 
    }
};

functionget(obj, desc) {
    var arr = desc.split(".");
    while(arr.length && (obj = obj[arr.shift()]));
    return obj;
}

functionreplaceTokens(HTML) {
    returnHTML.split('{{').map(function(i) { 
        var symbol = i.substring(0, i.indexOf('}}')).trim(); 
        return i.replace(symbol + '}}', get(translations, symbol)); 
    }).join('');
}

Solution 2:

You can use your regexp (with a little modification) to split your html in an array. Then you can replace only the template chunks of your array by their translations, and finally joining it and replacing the document html with it :

var html = "a little {{foo}} in the {{bar}}"; // replace with document.documentElement.innerHTMLvar translations = {foo: "boy", bar: "garden"};
var chunks = html.split(/({{[a-z.]+}})/g);
var chunksTranslated = chunks.map(function(chunk){
  if(chunk.slice(0,2)==="{{" && chunk.slice(-2)==="}}") {
    var id = chunk.slice(2,-2);
    return translations[id];
  }
  return chunk;
});
var translatedHtml = chunksTranslated.join("");
//document.documentElement.innerHTML = translatedHtml;

Solution 3:

Consider using an existing template engine, rather than building your own. There are a slew of them out there, and they're decently fast.

Evaluate a few options here: http://garann.github.io/template-chooser/

handlebarsjs seems to be the engine du jour.

John Ressig published a great "micro-templating" solution that is similar to your solution. (http://ejohn.org/blog/javascript-micro-templating/)

// Simple JavaScript Templating// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};

  this.tmpl = functiontmpl(str, data){
    // Figure out if we're getting a template, or if we need to// load the template - and be sure to cache the result.var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

      // Generate a reusable function that will serve as a template// generator (and which will be cached).newFunction("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}"with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");

    // Provide some basic currying to the userreturn data ? fn( data ) : fn;
  };
})();

You would use it against templates written like this (it doesn’t have to be in this particular manner – but it’s a style that I enjoy):

<scripttype="text/html"id="item_tmpl">
  <div id="<%=id%>"class="<%=(i % 2 == 1 ? " even" : "")%>">
    <divclass="grid_1 alpha right"><imgclass="righted"src="<%=profile_image_url%>"/></div><divclass="grid_6 omega contents"><p><b><ahref="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p></div>
  </div>
</script>

Post a Comment for "Javascript Replace "variables" In Html Code Faster"