![](/img/trans.png)
[英]How do I render my pug files to html on the client-side instead of server-side
[英]How do I include javascript files server-side?
我想在服務器端的另一個JS文件中包含JS文件,以防止從客戶端加載復制粘貼和多個JS文件。 就像PHP中的include('file.js')一樣。
沒有內置的方式可以包含來自JavaScript文件的其他JavaScript文件...但是您可以將它們添加到DOM->
function addJavascript(jsname,pos) {
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsname);
th.appendChild(s);
}
用法示例:
addJavascript('newExternal.js','body');
正如Superchargeging javascript文章建議的那樣-使用PHP,您可以閱讀所有.js文件並創建一個大的js文件,然后將其發送為一個文件。
這是本文示例的簡化,只是為了幫助您入門:
<?php
define('SCRIPT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/script/');
$files = array(
'jquery.js',
'myLib.js',
'site.js'
);
header('Content-Type: text/javascript');
foreach (files as $file) {
if (@readfile(SCRIPT_DIR . $file) === false) {
error_log("javascript.php: Error reading file '$file'");
}
}
?>
我還建議閱讀全文PHP中的Supercharging JavaScript,以獲取更多信息。
JSfile =“ 1.js,2.js,3.js”
循環
document.write();
您將必須使用腳本加載器 ,我想推薦在Twitter工作的Dustin Diaz的script.js
。 Github上的項目頁面 。 假設您要在頁面中加載一個jquery插件,這是您的使用方法,這是您應該做的
// load jquery and plugin at the same time. name it 'bundle'
$script(['jquery.js', 'my-jquery-plugin.js'], 'bundle')
// load your usage
$script('my-app-that-uses-plugin.js')
/*--- in my-jquery-plugin.js ---*/
$script.ready('bundle', function() {
// jquery & plugin (this file) are both ready
// plugin code...
})
/*--- in my-app-that-uses-plugin.js ---*/
$script.ready('bundle', function() {
// use your plugin :)
})
示例也來自項目頁面。 這是您應該遵循的步驟
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.