我希望在服务器端将一个JS文件包含到另一个JS文件中,以防止客户端复制粘贴和加载多个JS文件。就像PHP中使用include('file.js')一样。
我希望在服务器端将一个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');
<?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'");
}
}
?>
JSfile = "1.js, 2.js, 3.js"
for循环它
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 :)
})
示例也来自项目页面。以下是您应该遵循的步骤