在页面加载或刷新时加载随机js文件 [英] Load random js file on page load or refresh

查看:161
本文介绍了在页面加载或刷新时加载随机js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我,我可以加载一个随机JavaScript文件标记在HTML中?我知道这是可能的与CSS,但我想用JavaScript尝试。或者至少显示JavaScript代码有时是的有时没有。例如,我有两个名为1.js 2.js即可。如何在每页加载一个标签?

解决方案

此代码会在页面加载时随机加载JavaScript文件。

它会在列表JSFiles中随机选择一个文件,并将JS文件附加到头部部分。

 < HTML> 
< head>
< title>加载随机JS文件< / title>
< / head>
< script>
var JSFiles = ['1.js','2.js']; //把所有可能的JS文件加载。
函数randomJS(){
//从JSFiles列表中选择一个随机文件
var index = Math.floor(Math.random()* JSFiles.length);

//将JS文件附加到头部分。
var script = document.createElement('script');
script.src = JSFiles [index];
document.getElementsByTagName('head')[0] .appendChild(script);
};
< / script>
< body onload =randomJS();>

< / body>
< / html>


please help me, can i load a random javascript file tagged in html? I know this is possible with css, but I want to try with javascript. Or at least show javascript code sometimes yes sometimes no.

For example, i have two javascript files named "1.js" and "2.js". How i can tag one per page load?

解决方案

this code will randomly load a JavaScript file when the page loads.
it will pick a file randomly in the list JSFiles,
and append the JS file to the head section.

<html>
<head>
<title>Load Random JS file</title>
</head>
<script>
 var JSFiles = ['1.js','2.js']; // put all the possible JS files to load.
 function randomJS() {
     // pick a random file from the list in JSFiles
     var index = Math.floor(Math.random()*JSFiles.length); 

     // Append JS file to head section.
     var script = document.createElement('script');
     script.src = JSFiles[index];
     document.getElementsByTagName('head')[0].appendChild(script);
 };
</script>
<body onload="randomJS();">

</body>
</html>

这篇关于在页面加载或刷新时加载随机js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆