gpt4 book ai didi

javascript - 未在加载时定义

转载 作者:行者123 更新时间:2023-11-28 03:28:51 25 4
gpt4 key购买 nike

我知道这是一个反复出现的问题,但我找不到任何明确的解决方案。

我有一个静态 html/js,工作正常(因为它只有 html 和 js,脚本有时间加载,并且像 body onload 这样的东西正在工作)。

但现在我尝试在 Symfony 应用程序下导出同一页面

所以,在我的 Twig 上我有这个

<head>
{% block stylesheets %}
<link href="{{ asset('build/synopsis.css') }}" rel="stylesheet" />
{% endblock %}
{% block scripts %}
<script type="text/javascript" src="{{ asset('build/synopsis.js') }}"></script>
{% endblock %}
</head>

<body onload="drawStars()">

但现在显然,drawStars 函数的加载速度不够快,无法使其正常工作(或者我认为这就是发生的情况)。

我得到

Uncaught ReferenceError: drawStars is not defined at onload

我正在寻找一种方法来防止在脚本未完全加载之前生成我的全部正文。

PS:我知道在 header 中加载脚本是不好的,因为会减慢速度,但是在某些特定情况下,您希望首先完全加载脚本。已经尝试使用 asyncdefer 但没有成功。感谢您的帮助。

编辑:这是我的 synopsis.js 文件

require('../css/synopsis.css');

// Sets the number of stars we wish to display
const numStars = 100;

function drawStars() {
// For every star we want to display
for (let i = 0; i < numStars; i++) {
let star = document.createElement("div");
star.className = "star";
var xy = getRandomPosition();
star.style.top = xy[0] + 'px';
star.style.left = xy[1] + 'px';
document.body.append(star);
}
}


// Gets random x, y values based on the size of the container
function getRandomPosition() {
var y = window.innerWidth;
var x = window.innerHeight;
var randomX = Math.floor(Math.random()*x);
var randomY = Math.floor(Math.random()*y);
return [randomX,randomY];
}

var audio=document.createElement('audio');
var play=true;


function turn(){
if(play){
document.getElementsByClassName('soundOn')[0].innerHTML = "Musique Off";
document.getElementsByClassName('soundOn')[0].style.backgroundColor="red";
audio.src="musique/opening.mp3";
audio.play();
}else{
document.getElementsByClassName('soundOn')[0].innerHTML = "Musique On";
document.getElementsByClassName('soundOn')[0].style.backgroundColor="#4CAF50";
audio.pause();
}
play = !play;

}

最佳答案

等待脚本加载正文

<head>
{% block stylesheets %}
<link href="{{ asset('build/synopsis.css') }}" rel="stylesheet" />
{% endblock %}
{% block scripts %}
<script type="text/javascript" onload="drawStars()" src="{{ asset('build/synopsis.js') }}"></script>
{% endblock %}
</head>

<body>

但更逻辑地说,如果你必须在加载后从 js 函数内部运行一个函数,为什么不直接在文件的最后一行写入 drawStars() ,它就会自动执行一次已加载?!

关于javascript - 未在加载时定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58358564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com