我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
下面是Facebook如何为其微妙的Like按钮进行的一般版本:
<script> var firstScript = document.getElementsByTagName('script')[0], js = document.createElement('script'); js.src = 'https://cdnjs.cloudflare.com/ajax/libs/Snowstorm/20131208/snowstorm-min.js'; js.onload = function () { // do stuff with your dynamically loaded script snowStorm.snowColor = '#99ccff'; }; firstScript.parentNode.insertBefore(js, firstScript); </sc
如果它为Facebook工作,它会为你工作。
为什么我们正在寻找第一个脚本元素而不是头部或身体是因为一些浏览器不会创建一个如果缺乏,但我们保证有一个脚本元素 - 这个一个。
其他回答
var xxx = require("../lib/your-library.js")
或
import xxx from "../lib/your-library.js" //get default export
import {specificPart} from '../lib/your-library.js' //get named export
import * as _name from '../lib/your-library.js' //get full export to alias _name
如果您正在使用 Web 工作者,并希望在工作者的范围内添加额外的脚本,则其他关于添加脚本到标签标签等的答案不会为您工作。
幸运的是,网页工作者有自己的 importScripts 功能,这是在网页工作者的范围内的全球功能,原生于浏览器本身,因为它是规格的一部分。
否则,因为第二个最高的投票答案突出你的问题,RequireJS也可以处理包括在WebWorker内部的脚本(可能称之为ImportScripts本身,但有几个其他有用的功能)。
我创建了一个功能,它将允许你使用类似于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);
}
我有一个简单的问题,但我被这个问题的答案震惊。
我不得不使用一个变量(myVar1)定义在一个JavaScript文件(myvariables.js)在另一个JavaScript文件(main.js)。
為此,我做了下面的:
在 HTML 文件中下载了 JavaScript 代码,在正确的顺序中, myvariables.js 首先,然后 main.js:
<html>
<body onload="bodyReady();" >
<script src="myvariables.js" > </script>
<script src="main.js" > </script>
<!-- Some other code -->
</body>
</html>
文件: myvariables.js
var myVar1 = "I am variable from myvariables.js";
文件: main.js
// ...
function bodyReady() {
// ...
alert (myVar1); // This shows "I am variable from myvariables.js", which I needed
// ...
}
// ...
正如你所看到的,我在另一个JavaScript文件中使用了一个变量,但我不需要将一个添加到另一个文件中,我只需要确保第一个JavaScript文件在第二个JavaScript文件之前加载,并且,第一个JavaScript文件的变量在第二个JavaScript文件中可用,自动。
这拯救了我的日子,我希望这能帮助我。
您也可以使用 PHP 编写脚本:
文件 main.js.php:
<?php
header('Content-type:text/javascript; charset=utf-8');
include_once("foo.js.php");
include_once("bar.js.php");
?>
// Main JavaScript code goes here