将JS集成到JS中的干净方法


Clean way to integrate JS into JS

我的目标是从PHP生成一些JS。这是我script.php的内容

这样我可以稍后使用

<script src="script.php?id=1&username=tom"></script>

这是script.php 的内容

if (isset($_REQUEST["username"])) {
    $username=$_REQUEST["username"];
    $params.="&username=$username";
}
if (isset($_REQUEST["photo"])) {
    $photo=$_REQUEST["photo"];
    $params.="&photo=$photo";
}
?>
document.write('<link href="chat.css" rel="stylesheet" type="text/css" />');
window.jQuery || document.write('<script src="http://code.jquery.com/jquery-1.10.1.min.js"><'/script>');
document.write('<script src="chat.js.php<?=$params?>"></script>');
document.write('<div id="chatListUsers"></div>');
document.write('<div id="chatContainer"></div>');

有没有办法让它比:document.write("….")

一种模板系统?

document.write是向页面动态添加script标记的好方法,但更好的方法是使用这样的脚本加载程序。

但是,看起来你不想动态添加script,看起来你想用动态参数调用脚本,在这种情况下,你可以完全跳过document.write,只使用纯HTML,就像这样:

<script src="chat.js.php<?= $params ?>"></script>