Skip to content

Instantly share code, notes, and snippets.

@vfig
Created March 19, 2013 13:13
Show Gist options
  • Save vfig/5196004 to your computer and use it in GitHub Desktop.
Save vfig/5196004 to your computer and use it in GitHub Desktop.
An experiment with js that adds its source to the page when it runs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script>
"use strict";
function showme() {
var scripts = document.getElementsByTagName('script'),
ln = scripts.length,
script = scripts[ln - 1],
node = script.firstChild,
output = [],
showmeCall = /[ \t]*showme[ \t]*\([ \t]*\)[ \t]*;?[ \t]*\n?/g,
part, pre, code;
while (node) {
part = node.textContent;
part = part.replace(showmeCall, "");
output.push(part);
node = node.nextSibling;
}
document.write("\u003Cpre\u003E\u003Ccode\u003E");
document.write(output.join(""));
document.write("\u003C/code\u003E\u003C/pre\u003E");
}
</script>
</head>
<body>
<p>This is a test of the self-documenting javascript!</p>
<script>showme();
alert("Look! This script runs, and injects itself into the page!");
</script>
<p>Pretty neat, huh?</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment