繁体   English   中英

如何在服务器端包含javascript文件?

[英]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 :)
})

示例也来自项目页面。 这是您应该遵循的步骤

  1. 首先加载Script.js文件
  2. 现在包括依赖加载程序脚本,该脚本以异步方式加载所有其他想要的脚本[依赖加载程序脚本的内容与上面类似]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM