[英]How do I include javascript files server-side?
I want to include JS file inside another JS file, on server side, to prevent copy-paste and multiple JS files loading from client. 我想在服务器端的另一个JS文件中包含JS文件,以防止从客户端加载复制粘贴和多个JS文件。 Just like include('file.js') as PHP would do.
就像PHP中的include('file.js')一样。
There is no built in way to include other JavaScript files from a JavaScript file ... but you can add them into the DOM -> 没有内置的方式可以包含来自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);
}
Example usage : 用法示例:
addJavascript('newExternal.js','body');
As Supercharging javascript article suggest - with PHP you can read all your .js files and create one big js file that you will send in one piece. 正如Superchargeging javascript文章建议的那样-使用PHP,您可以阅读所有.js文件并创建一个大的js文件,然后将其发送为一个文件。
This is a simplification of the example from the article, just to get you started: 这是本文示例的简化,只是为了帮助您入门:
<?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'");
}
}
?>
I would also recommend to read the full article Supercharging JavaScript in PHP to get more info. 我还建议阅读全文PHP中的Supercharging JavaScript,以获取更多信息。
JSfile = "1.js, 2.js, 3.js" JSfile =“ 1.js,2.js,3.js”
for loop it 循环
document.write(); document.write();
You will have to use a script loader and i would like to recommend script.js
by Dustin Diaz who works at Twitter. 您将必须使用脚本加载器 ,我想推荐在Twitter工作的Dustin Diaz的
script.js
。 Project Page on Github . Github上的项目页面 。 Here is how you use it assuming you have a jquery plugin to be loaded in a page here is what you should do
假设您要在页面中加载一个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 :)
})
example is also from project page. 示例也来自项目页面。 Here are steps you should follow
这是您应该遵循的步骤
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.