📜 ⬆️ ⬇️

Using comments to store static data in Javascript

Sometimes the component created is associated with a large amount of static data. The only “normal” way to store this data in javascript is strings. But storing multiline data in rows is inconvenient, since each line requires additional formatting. In addition, you have to follow the shielding of characters.

In principle, this method lies on the surface, but not everyone thought about it in this aspect. In addition, a comment should be made here on minification. She should not cut helpful comments.

And so, all we need is to get the text content of the comment. But to get any comment through reflection is impossible. However, according to the specification, Function.prototype.toString () returns the textual representation of the function. Including comments. Therefore, we need to enclose our comment in the function body.

I will give an example. Somewhat contrived , but reflecting the essence. Storing styles in one file with js-component.
')
const Component = (function ($) { const initialize = (function () { var isInited = false; function css() { /*content-start .component, .component * { font-family: Arial; font-size: 12px; line-height: 1; color: #4D4D4D; padding: 0px; margin: 0px; } content-end*/ } return function () { if (isInited) return; isInited = true; (function () { const startStr = '/*content-start', endStr = 'content-end*/', fnStr = css.toString(), textStart = fnStr.indexOf(startStr) + startStr.length, textEnd = fnStr.lastIndexOf(endStr), text = fnStr.substring(textStart, textEnd).trim(); $(document.head).append($('<style type="text/css"/>').html(text)); })(); }; })(); return function () { initialize(); this.x = 5; this.y = 10; this.elem = $('<div class="component"/>').text('x = ' + this.x + '; y = ' + this.y); }; })(jQuery); 


And remember that any approach can be used both for evil and for good. It all depends on your goals.
All good)

Source: https://habr.com/ru/post/213009/


All Articles