我有一个网站,我希望它每次加载页面时随机加载一个不同的HTML5 Javascript动画,JavaScript是迄今为止我最弱的技能之一,我很感谢事先提供的任何帮助,如果碰巧是重复的(我已尝试搜索),然后对要关闭的问题进行投票。

基本上,我使用的方法是一种肮脏的方法,很可能是它无法正常工作的原因,基本上,我尝试了randommath并且没有运气,这归因于我的JS技能非常弱,看上去更简单的替代方法也不起作用并且基本上是在页面加载时插入HTML,例如a.html和b.html都包含不同的脚本。

这是我的代码如下所示:

的HTML

<html>
<head>
    <script src="js/insert.js"></script><!-- This inserts the Random Page -->
</head>
<body onload="loadExternalHTMLPage()">
    <div id="injectjs"> </div>
    <canvas="id"> </canvas>
<script src="js/animation-lib-pageA.js"></script><!--Library for pageA -->
<script src="js/animation-lib-pageB.js"></script><!--Library for pageB -->
</body>
</html>


Inject.js

function loadExternalHTMLPage() {

var xmlhttp;
var pagesToDisplay = ['a.html', 'b.html'];
if (window.XMLHttpRequest) {

xmlhttp = new XMLHttpRequest();

} else {

xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

}
xmlhttp.onreadystatechange = function () {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

document.getElementById("jsinsert").innerHTML = xmlhttp.responseText;

}

}
var randomnumber = Math.floor(Math.random() * pagesToDisplay.length);
xmlhttp.open("GET", pagesToDisplay[randomnumber], true);
xmlhttp.send();

}


大多数JS Guru都应该能够看到我是在页面加载时随机插入a.html和b.html的,现在可以了,但是问题是a.html和b.html中包含的脚本没有执行。 (使用萤火虫,我可以清楚地看到脚本已按预期插入)。

因此,例如a和b看起来像:

a.html

<script> window.onload = function () { }</script>


b.html

<script> window.onload = function () { } </script>


基本上,A和B中的代码是有效的,并且可以在此插入代码中正常工作,我已将以上示例仅作为占位符填充。 A和B都包含JavaScript,该JavaScript执行画布中包含的动画,但是目前不起作用,我怀疑这与在加载页面后加载脚本的事实有关。提前致谢。

最佳答案

您可以为A或B随机加载html,然后运行其动画。

本示例使用jQuery,这使加载远程html的任务更加容易。以下是jquery .load函数的链接,该函数将现有元素html替换为下载的html:http://api.jquery.com/load/如果要使用纯JavaScript,可以使用[messier!]替代方法,但是逻辑保持不变。

这些步骤是:


确保网页已加载,
随机选择A或B来加载/执行,
将#injectjs中的html替换为htmlForA或htmlForB,
等到html被完全替换后,
运行适当的animationA或animationB。


这是入门代码。 (确保您包括jQuery库)

<script>

window.onload(){

    // randomly load html+animation A or B

    if(Math.random()<.50){

        $('#injectjs').load(
              'yourSite.com/HtmlForA.html',   // first load the html for A
              function(){ animationA(); }     // then run animationA
        );

    }else{

        $('#injectjs').load(
              'yourSite.com/HtmlForB.html',   // first load the html for B
              function(){ animationB(); }     // then run animationB
        );

    }

}

</script>

关于javascript - 使用loadExternalHTMLPage在每个页面加载之间随机加载不同的JavaScript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17133729/

10-12 00:19
查看更多