我正在尝试使随机颜色函数加载得更快。目前,页面会先加载页面上的所有内容,然后再加载页眉中的随机颜色 div。该功能有效,但加载时间较长。以下是随机颜色函数的当前代码。
正文标签中是:
onload="return ran_col()" style="!important;"
正文中是一个 div,后面有一个脚本:
<div id="parallelogram" class="desktop-6 tablet-4 mobile-3">
<div id="logo" class="desktop-6 tablet-4 mobile-3">
<a href="/"><img src="{{ 'logo.png' | asset_url }}" alt="{{ shop.name }}" style="border: 0;"></a>
</div>
</div>
<script type="text/javascript">
function ran_col() { //function name
var color = '#'; // hexadecimal starting symbol
var letters = ['81ADB5','97C29D','E86A72','F1B36C', 'A37EA3', '277F92'];
color += letters[Math.floor(Math.random() * letters.length)];
document.getElementById('parallelogram').style.background = color; }
</script>
我正在尝试将此函数与 setTimeout()
结合起来,以便页面立即加载随机颜色 div。下面是我在 how to speed up your javascript 上的一篇文章中找到的示例:
var a = 3, b = 5;
function addNumbers (a, b) {
return (a+b);
}
// this will run the code immediately
setTimeout('var c = addNumbers(a,b)', 1);
console.log(c);
我已经尝试了几种配置,但我对 javascript 很陌生,并且没有任何运气来完成此任务。关于如何正确设置的任何建议?任何建议将不胜感激。预先感谢您。
最佳答案
您只需将您的函数暗示到 setTimeout 中即可:
function ran_col() { //function name
var color = '#'; // hexadecimal starting symbol
var letters = ['81ADB5','97C29D','E86A72','F1B36C', 'A37EA3', '277F92'];
color += letters[Math.floor(Math.random() * letters.length)];
document.getElementById('parallelogram').style.background = color; }
setTimeout(ran_col,1);
关于javascript - 如何正确编写异步加载函数的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27432820/