在使用CodePen时,JavaScript窗格中的JavaScript代码似乎就在</body>之前执行。在我的例子中,我在JavaScript中嵌入了一些JavaScript标记,其中引用了在JavaScript窗格中定义的函数。由于JS窗格是在</body>之前才计算的,所以我不能在<script>元素中引用这些JS函数。
是否有一种方法可以让CodePen有效地“将JavaScript窗格的内容放在<head>而不是</body>之前”?
发布于 2015-07-16 21:10:40
我最初希望能够指定JS窗格的内容包含在哪里:在关闭<head>元素或之前。默认情况下,CodePen会在CodePen关闭之前插入JS窗格内容,目前您无法对其采取任何措施(2015年7月)。
不过,你可以利用一些黑客来绕过这一问题。假设你的钢笔在:http://codepen.io/lanshen/pen/j7GB5q (我刚刚编的)。您的JS窗格有自己的URL:http://codepen.io/lanshen/pen/j7GB5q.js
在您的笔的“设置”中的“Settings for <head>”部分中,添加一个指向JS窗格的标记:
<script src="//codepen.io/lanshen/pen/j7GB5q.js"></script>这将导致JS窗格的内容包含在<head>中。这种方法的明显问题是JS窗格的内容仍将在</body>之前包含(也就是说,它将包含两次)。为了解决这个问题,我将我的JS窗格内容构造成一个if()/else(),以便if()块将加载到<head>中,而else块将在</body>之前加载。下面是我使用的JS窗格“模板”。同样,请确保像我前面提到的那样,在HTML的“make for <head>”一节中使用一个<head>标记引用JS窗格。
var headLoad;
if(!headLoad) { // when loaded in HEAD, headLoad will be falsey
headLoad = {}; // when loaded before </body>, headLoad will be truthy
(function() {
// PUT YOUR JS TO BE EXECUTED IN HEAD HERE...
alert("I am executing in the HEAD!");
headLoad.doSomething = function(mssg) {
// ...
alert(mssg);
};
})();
} else { // this code is not executed until just prior to </body>
// PUT YOUR JS TO BE EXECUTED PRIOR TO </body> HERE...
alert("The BODY is about to close....");
doSomething = function(mssg) {
alert(mssg);
};
doSomething("789");
}这里有一个小小的HTML窗格来测试它:
<p>ABC</p>
<script>
alert("I am in the HTML script tag.");
headLoad.doSomething("123"); // should alert
// The following will NOT execute because the "else" clause of the
// "if(!headLoad)" will not be executed until just prior to the </body>.
// the global doSomething() function is currently undefined.
doSomething("456"); // will NOT work, nor should it.
</script>
<p>XYZ</p>https://stackoverflow.com/questions/31437419
复制相似问题