必威体育Betway必威体育官网
当前位置:首页 > IT技术

js引入另外一个js

时间:2019-11-06 16:43:17来源:IT技术作者:seo实验室小编阅读:57次「手机版」
 

引入js

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 likeES6modulesto import modules, although this is not supported yet by most browsers. Many people using modules with browser applications usebuildand/ortranspilationtoolsto 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 it's way. According tothisStackOverflow answer, they are supported (but behind flags) in Chrome 60, Firefox 54 and MS Edge 15, 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.jsexport function hello() { return "Hello";}// main.jsimport {hello} from 'module'; // or './module'let val = hello(); // val is "Hello";

Node.js require

Node.js is currently using amodule.exports/requiresystem.You can usebabeltotranspile if you want theimportsyntax.

// mymodule.jsmodule.exports = { hello: function() { return "Hello"; }}// server.jsconst 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 useevaltorun it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Usingevalalsoopens the door to bugs, hacks and security issues.

jQuery Loading

ThejQuerylibraryprovides loading functionalityinone 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>tagcan 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>tagto end of the head section of the page, where thesrcattributeis set to the URL which is given to the function as the first parameter.

Both of these solutions are discussed and illustrated inJavaScriptMadness: Dynamic Script Loading.

Detecting when the script has been executed

Now, there is a big issue you must know about. Doing that implies thatyou remotelyload 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 yournewly loaded code the next line after you asked it to be loaded, because it will be still loading.

For example:my_lovely_script.jscontainsMySuperObject:

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 hittingF5.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. Forexample:

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 alambdafunction:

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 linescript.async= false;. There's agreatarticle on Javascript loading in generalwhich 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.

If anyone is looking for something more advanced, try outRequireJS.You'll get added benefits such as dependency management, better concurrency, and avoid duplication (that is, retrieving a script more than once).

You can write your JavaScript files in "modules" and then reference them as dependencies in other scripts. Or you can use RequireJS as a simple "go get this script" solution.

Example:

Define dependencies as modules:

some-dependency.js

文章最后发布于: 2019-01-24 15:37:05

相关阅读

译文 | 如何开始你的第一个线框图

无论你是用户体验设计的新手,还是你已经关注这个领域多年,你肯定知道线框图。线框图是将数字产品的想法转化为现实的关键一步。但线

职场新人,如何快速Hold住一个设计项目?

Goapi是一个测试工具类项目,前期团队面临的不单是产品体验升级的问题,而且在团队协作上,流程与规范问题也尤为突出。在今年4月份,业务

一个英文拼写纠错的思路(English Spelling check)

分享一个英文拼写纠错的思路,暂时无完整代码,后续如果实现会继续更新 英文拼写纠错这个问题由来已久,在这方面做的最好的就是谷歌了,

如何免费建立一个网站?

以我的个人经历来说,我是不太建议用免费的空间和域名来建立网店或网站。 我之前也建立了一个免费网站,开端的时分觉得真的挺不错的

一个完整的项目管理流程

一个完整的项目管理流程从一个项目提出到结束,按照ISO9001:2000的项目管理流程,大致有如下步骤: 1、产品立项报告 按照公司的

分享到:

栏目导航

推荐阅读

热门阅读