0

我有以下脚本,它在我的网站上生成大约 4000 行代码:

<script language="javascript" type="text/javascript">
<!--
var makemods2 = new Array;
<?php
$i = 0;
foreach ($makemods2 as $k=>$items) {
foreach ($items as $v) {
echo "makemods2[".$i++."] = new Array( '$k','".addslashes( $v->value )."','".addslashes( $v->text )."' );\n\t\t";
}
}
?>
//-->
</script>
<?php } ?>

这对页面加载来说真的很重,所以我当然想推迟解析。但是,由于它不是外部的,所以我不能使用 defer=defer。

我还阅读了来自谷歌的提示,这些提示建议使用这样的语法,但我不知道如何为上述代码编写:

<script language="javascript">
var node2 = document.createElement('script');
node2.type = 'text/javascript';
node2.async = true;
function switchDynaList2(listname,source,key,orig_key,orig_val){var list=eval("document.moduleForm."+listname);for(i in list.options.length){list.options[i]=null}i=0;for(x in source){if(source[x][0]==key){opt=new Option;opt.value=source[x][1];opt.text=source[x][2];if(orig_key==key&&orig_val==opt.value||i==0){opt.selected=true}list.options[i++]=opt}}list.length=i}
</script>

有什么建议么?

4

1 回答 1

0

AJAX is the way to go but as you seem to want to avoid that I would suggest:

Approach 1

Back in the day before AJAX and such handling of page load states, we used to put script tags at the end of the body tag. This would allow the body contents to be parsed, without being delayed by the script execution. Then all you need to do is default your dropdowns to disabled and enable them when the script finishes executing.

Note:

  • Some styling issues may occur.
  • This approach to some is considered deprecated.

Approach 2

Move the PHP code into it's own page and include the script using the src attribute of the script tag. You can then use defer attribute on the script tag.

于 2012-03-14T01:42:29.897 回答