JavaScript is the new black and each and everyone has re-discovered JavaScript and it’s inevitable not to have JavaScript as one of your tools. Especially if you’re working with SharePoint, Office or Office 365 Apps or Add-Ins.

In this short post I’m just documenting and sharing a small and nifty JavaScript hack that is very handy when you’re doing for instance JavaScript injection, one of the most popular customization patterns for Office 365 and SharePoint Online at the moment. I often find myself in the situation that I need to deploy and inject a JavaScript file and an accompanying CSS file. More than often both the JS file and the CSS file is very small and I’ve found it very handy to combine the JS and CSS file into one JS file.

Keep calm…Unfortunately the multi-line string features in JavaScript sucks, at best, unless you know this little trick. For instance you need to end each line with a backslash (\) and if you need line breaks you need to insert backslash + n (\n). If you’re working with a CSS tool or like to write your CSS then it’s annoying to add all that extra fluff when copying and pasting the CSS.

So instead I’ve been using a technique that involves creating a small function like this:

Wictor.MultiString = function (f) {
    return f.toString().split('\n').slice(1, -1).join('\n');
}

Using this function (and hack) I can now write multi-line strings as follows, and that allows me to copy-paste CSS from any tool without redecorating it in JavaScript.

Wictor.CSS = Wictor.MultiString(function(){/**
 body {
     font-family: Consolas !Important;
 }
 **/});

I can then use this method like this, in for instance SharePoint Online, to inject some CSS without deploying a CSS file:

var Wictor = Wictor || {}

Wictor.MultiString = function (f) {
    return f.toString().split('\n').slice(1, -1).join('\n');
}

Wictor.CSS = Wictor.MultiString(function(){/**
 body {
    font-family: Consolas !Important;
 }
 **/});
 
 (function () {
    ExecuteOrDelayUntilScriptLoaded(function() {
        var css = document.createElement("style");
        css.type = "text/css";
        css.innerHTML = Wictor.CSS;
        document.body.appendChild(css);
        alert('You\'re injected')
    }, 'sp.js');
 })();

Happy JavaScripting….