vladkrasovsky
11/23/2016 - 9:45 AM

Lazyeval strict mode

Lazyeval strict mode

function trim(str) {
  return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g,'');
}

function stripOutCommentBlock(code) {
    return code.replace(/^[\s\xA0]+\/\*|\*\/[\s\xA0]+$/g, "")
}

function lazyEval(id) {
    var lazyElement = document.getElementById(id);
    var lazyElementBody = lazyElement.innerHTML;
    var jsCode = stripOutCommentBlock(lazyElementBody);
    var script;

    // based on https://github.com/jquery/jquery/commit/feea9394b75a5dcb16fad013a402b388f97cefba
    if ( trim(jsCode).indexOf("use strict") === 1 ) {
      script = document.createElement("script");
      script.text = jsCode;
      document.head.appendChild(script).parentNode.removeChild(script);
    } else {
      (0,eval)(jsCode);
    }
}

// Function call somewhere in the code:
// -------------------------------------
 
lazyEval('myjscode');
<html>
<body>

<!-- ----------------------------------------------- -->
<!-- inline script block with commented code inside: -->
<!-- ----------------------------------------------- -->

<script id="myjscode">
/*
'use strict';(function(h,v){function q(b){if(""===m)return b;
b=b.charAt(0).toUpperCase()+b.substr(1);
return m+b}var f=Math,A=v.createElement("div").style,m;a:{for(var...
*/
</script>

</body>
</html>