我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
我基本上做如下,创建一个新的元素,并添加它来主导:
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);
在 jQuery 中:
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// Script is now loaded and executed.
// Put your dependent JavaScript code here.
});
其他回答
从.mix 文件中的混合文档:
混合文件只是.js 或.css 文件与.mix. 在文件名中. 混合文件只是扩展正常风格或脚本文件的功能,并允许您进口和结合。
以下是一個.mix 檔案的例子,將多個.js 檔案組成一個:
// scripts-global.mix.js
// Plugins - Global
@import "global-plugins/headroom.js";
@import "global-plugins/retina-1.1.0.js";
@import "global-plugins/isotope.js";
@import "global-plugins/jquery.fitvids.js";
混合输出这个作为脚本-global.js 以及作为一个小型版本(脚本-global.min.js)。
注意:我不以任何方式与混合,除了使用它作为一个前端开发工具. 我遇到了这个问题,看到一个混合JavaScript文件在行动(在一个混合板)并有点混淆它(“你可以这样做吗?”我认为自己)。 然后我意识到这是一个应用程序特定的文件类型(有些令人失望,同意)。
如果你想要一个单一的链接到所有的JavaScript功能,它们位于不同的文件,你可以做这样的事情,使用PHP:
创建一个 php 文件,将存储所有的 javascript 功能/triggers javascript.php 并确保它是一个.php 文件:
在你的“头”部分
<script src="/directory/javascript.php"></script>
在您的 javascript.php 中,创建一个包含内容类型的应用程序/javascript 标题,并使用 php glob 包含所有 javascript 文件/脚本如下:
饰 JavaScript.php
<?php
header("content-type:application/javascript");
foreach(glob("/functions/*.js") as $filename){include($filename);}
?>
现在,你可以创建单独的JavaScript文件并将其添加到你的 / 功能文件夹,或者你可以称之为什么。
$("head").append($("<script></script>").attr("src", url));
/* Note that following line of code is incorrect because it doesn't escape the
* HTML attribute src correctly and will fail if `url` contains special characters:
* $("head").append('<script src="' + url + '"></script>');
*/
但是,这个方法也有一个问题:如果一个错误发生在进口的JavaScript文件,Firebug(以及Firefox Error Console和Chrome Developer Tools也)将报告其位置错误,这是一个很大的问题,如果你使用Firebug跟踪JavaScript错误很多(我做)。
但是,如果这不是一个问题,那么这个方法应该工作。
我實際上寫了一個名為 $.import_js() 的 jQuery 插件,使用此方法:
(function($)
{
/*
* $.import_js() helper (for JavaScript importing within JavaScript code).
*/
var import_js_imported = [];
$.extend(true,
{
import_js : function(script)
{
var found = false;
for (var i = 0; i < import_js_imported.length; i++)
if (import_js_imported[i] == script) {
found = true;
break;
}
if (found == false) {
$("head").append($('<script></script').attr('src', script));
import_js_imported.push(script);
}
}
});
})(jQuery);
因此,所有你需要做才能进口JavaScript是:
$.import_js('/path_to_project/scripts/somefunctions.js');
我也做了一个简单的测试为这个例子。
它包含主.js 文件在主 HTML 中,然后在主.js 中的脚本使用 $.import_js() 来导入一个名为 included.js 的额外文件,该文件定义了此功能:
function hello()
{
alert("Hello world!");
}
(这个答案是回复e-satis的评论)。
我只是写了这个JavaScript代码(使用DOM操作的Prototype):
var require = (function() {
var _required = {};
return (function(url, callback) {
if (typeof url == 'object') {
// We've (hopefully) got an array: time to chain!
if (url.length > 1) {
// Load the nth file as soon as everything up to the
// n-1th one is done.
require(url.slice(0, url.length - 1), function() {
require(url[url.length - 1], callback);
});
} else if (url.length == 1) {
require(url[0], callback);
}
return;
}
if (typeof _required[url] == 'undefined') {
// Haven't loaded this URL yet; gogogo!
_required[url] = [];
var script = new Element('script', {
src: url,
type: 'text/javascript'
});
script.observe('load', function() {
console.log("script " + url + " loaded.");
_required[url].each(function(cb) {
cb.call(); // TODO: does this execute in the right context?
});
_required[url] = true;
});
$$('head')[0].insert(script);
} else if (typeof _required[url] == 'boolean') {
// We already loaded the thing, so go ahead.
if (callback) {
callback.call();
}
return;
}
if (callback) {
_required[url].push(callback);
}
});
})();
使用:
<script src="prototype.js"></script>
<script src="require.js"></script>
<script>
require(['foo.js','bar.js'], function () {
/* Use foo.js and bar.js here */
});
</script>
地址: http://gist.github.com/284442.
我创建了一个功能,它将允许你使用类似于C#/Java的语法,以包含一个JavaScript文件。我已经测试了一点甚至从另一个JavaScript文件的内部,它似乎工作。
我把这个代码放在我的脚本目录的根源文件(我称之为 global.js,但你可以使用你想要的任何东西. 除非我错了这个和jQuery应该是唯一需要的脚本在一个特定的页面上. 请记住,这在很大程度上是未测试的某些基本使用,所以可能或可能没有任何问题与我做了的方式; 使用在自己的风险,我没有责任,如果你 scr
/**
* @fileoverview This file stores global functions that are required by other libraries.
*/
if (typeof(jQuery) === 'undefined') {
throw 'jQuery is required.';
}
/** Defines the base script directory that all .js files are assumed to be organized under. */
var BASE_DIR = 'js/';
/**
* Loads the specified file, outputting it to the <head> HTMLElement.
*
* This method mimics the use of using in C# or import in Java, allowing
* JavaScript files to "load" other JavaScript files that they depend on
* using a familiar syntax.
*
* This method assumes all scripts are under a directory at the root and will
* append the .js file extension automatically.
*
* @param {string} file A file path to load using C#/Java "dot" syntax.
*
* Example Usage:
* imports('core.utils.extensions');
* This will output: <script type="text/javascript" src="/js/core/utils/extensions.js"></script>
*/
function imports(file) {
var fileName = file.substr(file.lastIndexOf('.') + 1, file.length);
// Convert PascalCase name to underscore_separated_name
var regex = new RegExp(/([A-Z])/g);
if (regex.test(fileName)) {
var separated = fileName.replace(regex, ",$1").replace(',', '');
fileName = separated.replace(/[,]/g, '_');
}
// Remove the original JavaScript file name to replace with underscore version
file = file.substr(0, file.lastIndexOf('.'));
// Convert the dot syntax to directory syntax to actually load the file
if (file.indexOf('.') > 0) {
file = file.replace(/[.]/g, '/');
}
var src = BASE_DIR + file + '/' + fileName.toLowerCase() + '.js';
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
$('head').find('script:last').append(script);
}
推荐文章
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- Android Studio突然无法解析符号
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?