我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?


当前回答

如果您正在使用 Web 工作者,并希望在工作者的范围内添加额外的脚本,则其他关于添加脚本到标签标签等的答案不会为您工作。

幸运的是,网页工作者有自己的 importScripts 功能,这是在网页工作者的范围内的全球功能,原生于浏览器本身,因为它是规格的一部分。

否则,因为第二个最高的投票答案突出你的问题,RequireJS也可以处理包括在WebWorker内部的脚本(可能称之为ImportScripts本身,但有几个其他有用的功能)。

其他回答

我有一个简单的问题,但我被这个问题的答案震惊。

我不得不使用一个变量(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文件中可用,自动。

这拯救了我的日子,我希望这能帮助我。

对于 Node.js 而言,这对我来说是最好的!

我在这里尝试了很多解决方案,但没有一个帮助我只是能够在没有改变范围的情况下加载另一个文件。

const fs = require('fs');
eval(fs.readFileSync('file.js') + '');

下面是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工作,它会为你工作。

为什么我们正在寻找第一个脚本元素而不是头部或身体是因为一些浏览器不会创建一个如果缺乏,但我们保证有一个脚本元素 - 这个一个。

现在,我可能完全被误导了,但这里是我最近开始做的事情......开始和结束你的JavaScript文件与运输返回,在PHP脚本中放置,随后另一个运输返回。

技术上,你不需要评论,但它在Dreamweaver中发布错误,这让我感到不安. 如果你在一个不发布错误的IDE中编写,你不需要评论或运输回来。

\n
//<?php require_once("path/to/javascript/dependency.js"); ?>

function myFunction(){
    // stuff
}
\n

与 $.getScript 和实际上任何其他解决方案需要一个呼叫回复,当加载完成时的问题是,如果你有多个文件使用它,并依赖对方,你已经没有办法知道什么时候所有的脚本被加载(一旦它们被纳入多个文件)。

文件3JS

var f3obj = "file3";

// Define other stuff

文件2JS:

var f2obj = "file2";
$.getScript("file3.js", function(){

    alert(f3obj);

    // Use anything defined in file3.
});

此分類上一篇: JS

$.getScript("file2.js", function(){
    alert(f3obj); //This will probably fail because file3 is only guaranteed to have loaded inside the callback in file2.
    alert(f2obj);

    // Use anything defined in the loaded script...
});

您可以尝试使用 $.when 检查一系列丢失的对象,但现在您正在做这一点在每个文件和文件2 将被视为加载,一旦 $.when 执行,而不是当呼叫回复执行,所以文件1 仍然继续执行之前文件3 被加载,这真的仍然有相同的问题。

我喜欢延长jQuery的想法,但显然你不需要。

在呼叫document.writeln之前,它检查以确保脚本已经没有被加载,通过评估所有脚本元素。

而不是这个方法,你可以尝试修改 jQuery readyList,但这似乎是一个更糟糕的解决方案。

解决方案:

$.extend(true,
{
    import_js : function(scriptpath, reAddLast)
    {
        if (typeof reAddLast === "undefined" || reAddLast === null)
        {
            reAddLast = true; // Default this value to true. It is not used by the end user, only to facilitate recursion correctly.
        }

        var found = false;
        if (reAddLast == true) // If we are re-adding the originating script we do not care if it has already been added.
        {
            found = $('script').filter(function () {
                return ($(this).attr('src') == scriptpath);
            }).length != 0; // jQuery to check if the script already exists. (replace it with straight JavaScript if you don't like jQuery.
        }

        if (found == false) {

            var callingScriptPath = $('script').last().attr("src"); // Get the script that is currently loading. Again this creates a limitation where this should not be used in a button, and only before document.ready.

            document.writeln("<script type='text/javascript' src='" + scriptpath + "'></script>"); // Add the script to the document using writeln

            if (reAddLast)
            {
                $.import_js(callingScriptPath, false); // Call itself with the originating script to fix the order.
                throw 'Readding script to correct order: ' + scriptpath + ' < ' + callingScriptPath; // This halts execution of the originating script since it is getting reloaded. If you put a try / catch around the call to $.import_js you results will vary.
            }
            return true;
        }
        return false;
    }
});

使用:

var f3obj = "file3";

// Define other stuff
$(function(){
    f3obj = "file3docready";
});

文件2:

$.import_js('js/file3.js');
var f2obj = "file2";
$(function(){
    f2obj = "file2docready";
});

文件1:

$.import_js('js/file2.js');

// Use objects from file2 or file3
alert(f3obj); // "file3"
alert(f2obj); // "file2"

$(function(){
    // Use objects from file2 or file3 some more.
    alert(f3obj); //"file3docready"
    alert(f2obj); //"file2docready"
});