对.js文件依赖包含html中声明的变量是一个好习惯 [英] Is it a good practice for a .js file to rely on variables declared in the including html

查看:120
本文介绍了对.js文件依赖包含html中声明的变量是一个好习惯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之:

<script type="text/javascript">
    var root = '${config.root}';
    var userLanguage = '${config.language}';
    var userTimezone = '${config.timezone}';
</script>
<script type="text/javascript" src="js/scripts.js"></script>

然后,在 scripts.js 中,依赖这些变量:

And then, in scripts.js, rely on these variables:

if (userLanguage == 'en') { .. }

$ {..} 只是脚本中占位符号的占位符生成页面。它可以是php,jsp,asp,等等。关键是 - 它是动态的,因此它不能成为 .js 文件的一部分(这是静态的)。

The ${..} is simply a placeholder for a value in the script that generates the page. It can be php, jsp, asp, whatever. The point is - it is dynamic, and hence it can't be part of the .js file (which is static).

那么,静态javascript文件可以依赖这些外部定义的配置变量吗? (当然,它们主要是配置)。

So, is it OK for the static javascript file to rely on these externally defined configuration variables? (they are mainly configuration, of course).

或者首选服务 .js 文件也是动态的(即使用正确的 Content-Type 将其设为.php / .jsp),并在那里定义这些值。

Or is it preferred to make the .js file be served dynamically as well (i.e. make it a .php / .jsp, with the proper Content-Type), and have these values defined in there.

推荐答案

您可以按照中使用的示例进行操作jquery插件。它们以特定格式定义参数的默认值,这些格式可能会被用户重载。所以在我看来,允许用户以外部脚本使用的文档格式定义一些变量是可以的。

You could follow the example used in jquery plugins. They define default values for the parameters in a specific format which could be overloaded by the user. So in my opinion it is OK to allow the user the possibility to define some variables in a documented format which would be used by the external script.

这篇关于对.js文件依赖包含html中声明的变量是一个好习惯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆