在定义之前引用函数

时间:2014-06-23 12:01:42

标签: javascript html

我已经读过如果你想让它看起来像你的网站加载更快,那么你应该把你的javascript放在你的html文件的末尾,如下所示

<html>
<body>
</body>
<script>
//my awesome javascript functions go here because it lets things load faster 
//than if it was at the top
</script>
</html>

问题在于我创建按钮或使用调用这些函数的onChange事件。 我是怎么想把我的JS放在页面的底部并且在它读取js函数需要被调用的时候定义了JS?

例如

<html>
<body>
<input type="text" onChange="myfunction()"/>
</body>
<script>
function myfunction(){}
</script>
</html>

我在伪代码中执行了代码 - 所以你不会专注于我的任何语法错误,而是更多地关注我的意思。 在创建页面时,它会正确创建html,但是会给我一个控制台错误,说明&#34; myfunction&#34;没有定义。 如果我将脚本部分移动到正文上方,则可以使用,但建议将其保持最后以提高页面加载速度。

请注意我没有使用jquery。

我原本以为这是重复的(Javascript at the bottom, function call in the body?),但它似乎没有回答我的问题。

------------------------更新---------------------- ------ 使用事件监听器

<html>
    <body>
    <input type="text" id="myawesometext"/>
    </body>
    <script>
    function myfunction(){}
    element = document.getElementById('myawesometext');
    element.addEventListener("onChange", myfunction, false);
    </script>
    </html>

0 个答案:

没有答案