Skip to content

Instantly share code, notes, and snippets.

@smhmic
Last active July 28, 2017 19:46
Show Gist options
  • Save smhmic/474ce1b21b338064db2c to your computer and use it in GitHub Desktop.
Save smhmic/474ce1b21b338064db2c to your computer and use it in GitHub Desktop.
Javascript HEREDOC (and simple method for injecting CSS as style block)
/** Created by stephen on 3/12/15. */
'use strict';
/**
* Convenience function for hardocding multiline strings, without needing use explicit "\n" and concatenate lines.
* @param {function} fn - A function with a block comment as it's entire definition. Will not be executed.
* @return {string} The contents of the block comment in the definition of @param fn.
*/
function HEREDOC( fn ){
return fn.toString().match( /\/\*[\n\l]?([\s\S]*?)\*\//m )[1];
};
///////////////
// EXAMPLE 1 //
///////////////
console.log( HEREDOC( function(){/*
This
is
a
test
*/}));
///////////////
// EXAMPLE 2 //
///////////////
/**
* Add css into the current document.
* @param {string} css - The CSS to parse. Can includ line comments (non-CSS) by beginning line with "//".
* @param {boolean} removeLineComments - Optional. If true, will remove lines starting with "//". Otherwise, will convert to CSS-style block comments.
*/
function injectCss( css, removeLineComments ){
var el = document.createElement('style');
el.innerHTML = css.replace(/[\s\n]\/\/\s?(.*)$/mg, removeLineComments ? '' : '/* $1 */' );
document.head.appendChild( el );
}
injectCss( HEREDOC( function(){/*
// Outline everything!
* { border: 1px solid green; }
// Fade everything!
html { opacity: 0.5; }
*/}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment