你真的应该使用按需 JavaScript。只加载 90% 的用户会使用的内容。对于大多数人不会使用的东西,请将它们分开并按需加载。此外,如果压缩后的 JavaScript 超过 2 兆字节,你应该认真重新考虑你在做什么。
function ondemand(url,f,exe)
{
if (eval('typeof ' + f)=='function') {eval(f+'();');}
else
{
var h = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('defer','defer');
js.setAttribute('src','scripts/'+url+'.js');
js.setAttribute('type',document.getElementsByTagName('script')[0].getAttribute('type'));
h.appendChild(js);
ondemand_poll(f,0,exe);
h.appendChild(document.createTextNode('\n'));
}
}
function ondemand_poll(f,i,exe)
{
if (i<200) {setTimeout(function() {if (eval('typeof ' + f)=='function') {if (exe==1) {eval(f+'();');}} else {i++; ondemand_poll(f,i,exe);}},50);}
else {alert('Error: could not load \''+f+'\', certain features on this page may not work as intended.\n\nReloading the page may correct the problem, if it does not check your internet connection.');}
}
示例用法:加载example.js
(第一个参数),轮询函数example_init1()
(第二个参数)和1
(第三个参数)意味着一旦轮询找到它就执行该函数......
function example() {ondemand('example','example_init1',1);}