在 HTML 中嵌入要点很容易,只需包含下面的代码,浏览器就会在页面加载时获取资源。
<script src="https://gist.github.com/Xeoncross/eec39effbe6b9c421fec.js"></script>
但是,我正在尝试解析页面以查找短代码并用脚本标记替换这些文本节点。
[gist:eec39effbe6b9c421fec]
不幸的是,它似乎没有发射。
function loadGist(element, gistId) {
var callbackName = "gist_callback";
window[callbackName] = function (gistData) {
console.log('Made it!');
delete window[callbackName];
var html = '<link rel="stylesheet" href="' + gistData.stylesheet + '"></link>';
html += gistData.div;
console.log(element.innerHTML);
element.innerHTML = html;
script.parentNode.removeChild(script);
//element.parentNode.insertBefore(element, node);
//node.parentNode.removeChild(node);
};
var script = document.createElement("script");
script.setAttribute("src", "https://gist.github.com/" + gistId + ".json?callback=" + callbackName);
document.body.appendChild(script);
//return script;
}
function traverseChildNodes(node) {
var next;
if (node.nodeType === 1) {
// (Element node)
if (node = node.firstChild) {
do {
// Recursively call traverseChildNodes
// on each child node
next = node.nextSibling;
traverseChildNodes(node);
} while(node = next);
}
} else if (node.nodeType === 3) {
// (Text node)
if (/\[(\w+):([^\]]+)\]/g.test(node.data)) {
// Do something interesting here
console.log('found it', node);
//<script src=""></script>
var script = document.createElement("script");
script.setAttribute("src", "https://gist.github.com/Xeoncross/eec39effbe6b9c421fec.js");
//document.body.appendChild(script);
var script = loadGist(node, 'eec39effbe6b9c421fec');
/*
var parent = node.parentNode;
console.log(parent);
parent.insertBefore(script, node);
parent.removeChild(node);
*/
//node.parentNode.insertBefore(script, node);
//node.parentNode.removeChild(node);
}
}
}
var $body = document.getElementsByTagName("body")[0];
traverseChildNodes($body);
哦,我正在用香草 Javascript 做这一切——请不要使用 jQuery。