如何在另一个JavaScript文件中包含JavaScript文件? [英] How do I include a JavaScript file in another JavaScript file?

查看:100
本文介绍了如何在另一个JavaScript文件中包含JavaScript文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CSS中是否存在类似于 @import 的内容,允许您在另一个JavaScript文件中包含JavaScript文件?

解决方案

旧版本的JavaScript没有导入,包含或要求,因此开发了许多不同的方法来解决这个问题。



但最新版本的JavaScript有像 ES6模块这样的标准来导入模块,尽管大多数浏览器都不支持。许多使用浏览器应用程序模块的人使用构建和/或 transpilation 工具,可以使用带有模块等功能的新语法。



ES6模块



请注意,目前,对ES6模块的浏览器支持并不是特别好,但它正在发展中。根据此StackOverflow答案,Chrome 61,Firefox 54支持它们(在 dom.moduleScripts后面)。启用设置关于:config )和MS Edge 16,只有Safari 10.1提供不带标记的支持。



因此,您目前仍需要使用构建和/或转换工具来运行有效的JavaScript,而无需用户使用这些浏览器版本或启用任何标记。



一旦ES6模块很常见,下面就是你如何使用它们:

  // module.js 
导出函数hello(){
返回Hello;
}



  // main.js 
从'module'导入{hello}; //或'./module'
let val = hello(); // val是你好;



Node.js require



节点。 js目前正在使用 module.exports / require 系统。如果需要 import 语法,可以使用 babel 进行转换。

  // mymodule.js 
module.exports = {
hello :function(){
returnHello;
}
}



  // server.js 
const myModule = require('./ mymodule');
let val = myModule.hello(); // val是Hello

JavaScript还有其他方法可以在浏览器中包含外部JavaScript内容不需要预处理。



AJAX加载



您可以使用AJAX调用加载其他脚本然后使用 eval 来运行它。这是最简单的方法,但由于JavaScript沙箱安全模型,它仅限于您的域。使用 eval 也会打开错误,黑客和安全问题的大门。



jQuery Loading



jQuery 库提供加载功能在一行中

  $。getScript(my_lovely_script.js,function(){
alert(加载脚本但不一定执行。);
});



动态脚本加载



你可以添加带有脚本URL的脚本标记到HTML中。为了避免jQuery的开销,这是一个理想的解决方案。



该脚本甚至可以驻留在不同的服务器上。此外,浏览器评估代码。 < script> 标记可以注入网页< head> ,也可以插入到网页之前关闭< / body> 标记。



以下是一个如何运作的示例:

  function dynamicLoadScript(url){
var script = document.createElement(script); //创建一个脚本DOM节点
script.src = url; //将它的src设置为提供的URL

document.head.appendChild(script); //将它添加到页面头部的末尾(可以将'head'更改为'body',将其添加到body部分的末尾)
}

此函数会将新的< script> 标记添加到head部分的末尾该页面的 src 属性设置为作为第一个参数赋予函数的URL。



这些解决方案都在 JavaScript疯狂:动态脚本加载中进行了讨论和说明。



检测脚本何时执行



现在,您必须了解一个大问题。这样做意味着您远程加载代码。现代Web浏览器将加载文件并继续执行当前脚本,因为它们异步加载所有内容以提高性能。 (这适用于jQuery方法和手动动态脚本加载方法。)



这意味着如果你直接使用这些技巧,你将不会在你要求加载之后,能够在下一行使用新加载的代码,因为它仍然会加载。



例如: my_lovely_script.js 包含 MySuperObject

  var js = document.createElement(script); 

js.type =text / javascript;
js.src = jsFilePath;

document.body.appendChild(js);

var s = new MySuperObject();

错误:MySuperObject未定义

然后重新加载页面 F5 。它的工作原理!令人困惑......



那该怎么办?



嗯,你可以在我给你的链接中使用作者建议的黑客。总之,对于匆忙的人,他在加载脚本时使用事件来运行回调函数。因此,您可以使用远程库将所有代码放在回调函数中。例如:

  function loadScript(url,callback)
{
//在
var head = document.getElementsByTagName('head')[0]之前按照建议将脚本标记添加到头部;
var script = document.createElement('script');
script.type ='text / javascript';
script.src = url;

//然后将事件绑定到回调函数。
//有多个事件可以实现跨浏览器兼容性。
script.onreadystatechange = callback;
script.onload = callback;

//开始加载
head.appendChild(脚本);
}

然后在脚本加载到脚本之后编写要使用的代码 lambda function

  var myPrettyCode = function(){
//在这里,做任何你想要的事情
};

然后你运行所有:

  loadScript(my_lovely_script.js,myPrettyCode); 

请注意,脚本可能在DOM加载之后或之前执行,具体取决于浏览器以及是否你包括 script.async = false; 这一行。这里有一篇关于Javascript加载的精彩文章。 / p>

源代码合并/预处理



如本答案顶部所述,许多开发人员现在使用构建/转换像项目中的WebPack,Babel或Gulp这样的工具,允许他们更好地使用新的语法和支持模块,组合文件,缩小等等。


Is there something in JavaScript similar to @import in CSS that allows you to include a JavaScript file inside another JavaScript file?

解决方案

The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed.

But recent versions of JavaScript have standards like ES6 modules to import modules, although this is not supported yet by most browsers. Many people using modules with browser applications use build and/or transpilation tools to make it practical to use new syntax with features like modules.

ES6 Modules

Note that currently, browser support for ES6 Modules is not particularly great, but it is on its way. According to this StackOverflow answer, they are supported in Chrome 61, Firefox 54(behind the dom.moduleScripts.enabled setting in about:config) and MS Edge 16, with only Safari 10.1 providing support without flags.

Thus, you will currently still need to use build and/or transpilation tools to valid JavaScript that will run in without any requirement for the user to use those browser versions or enable any flags.

Once ES6 Modules are commonplace, here is how you would go about using them:

// module.js
export function hello() {
  return "Hello";
}

// main.js
import {hello} from 'module'; // or './module'
let val = hello(); // val is "Hello";

Node.js require

Node.js is currently using a module.exports/require system. You can use babel to transpile if you want the import syntax.

// mymodule.js
module.exports = {
   hello: function() {
      return "Hello";
   }
}

// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"   

There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing.

AJAX Loading

You could load an additional script with an AJAX call and then use eval to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval also opens the door to bugs, hacks and security issues.

jQuery Loading

The jQuery library provides loading functionality in one line:

$.getScript("my_lovely_script.js", function() {
   alert("Script loaded but not necessarily executed.");
});

Dynamic Script Loading

You could add a script tag with the script URL into the HTML. To avoid the overhead of jQuery, this is an ideal solution.

The script can even reside on a different server. Furthermore, the browser evaluates the code. The <script> tag can be injected into either the web page <head>, or inserted just before the closing </body> tag.

Here is an example of how this could work:

function dynamicallyLoadScript(url) {
    var script = document.createElement("script"); // Make a script DOM node
    script.src = url; // Set it's src to the provided URL

    document.head.appendChild(script); // Add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
}

This function will add a new <script> tag to end of the head section of the page, where the src attribute is set to the URL which is given to the function as the first parameter.

Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading.

Detecting when the script has been executed

Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. (This applies to both the jQuery method and the manual dynamic script loading method.)

It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

For example: my_lovely_script.js contains MySuperObject:

var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

Then you reload the page hitting F5. And it works! Confusing...

So what to do about it ?

Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses an event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:

function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

Then you write the code you want to use AFTER the script is loaded in a lambda function:

var myPrettyCode = function() {
   // Here, do whatever you want
};

Then you run all that:

loadScript("my_lovely_script.js", myPrettyCode);

Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line script.async = false;. There's a great article on Javascript loading in general which discusses this.

Source Code Merge/Preprocessing

As mentioned at the top of this answer, many developers now use build/transpilation tool(s) like WebPack, Babel, or Gulp in their projects, allowing them to use new syntax and support modules better, combine files, minify, etc.

这篇关于如何在另一个JavaScript文件中包含JavaScript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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