在Javascript文件中包含其他Javascript文件的方法
mob 发布于 2021-07-23

1、从Safari 10.1、Chrome 61、Firefox 60和Edge 16开始,浏览器就支持直接加载ECMAScript模块(不需要像Webpack这样的工具)。不需要使用Node.js'.mjs扩展;浏览器完全忽略模块/脚本上的文件扩展名。

<script type="module">
  import { hello } from './hello.mjs'; // Or it could be simply `hello.js`
  hello('world');
</script>
// hello.mjs -- or it could be simply `hello.js`
export function hello(text) {
  const div = document.createElement('div');
  div.textContent = `Hello ${text}`;
  document.body.appendChild(div);
}

阅读更多信息https://jakearchibald.com/2017/es-modules-in-browsers/

浏览器中的动态导入

<script type="module">
  import('hello.mjs').then(module => {
      module.hello('world');
    });
</script>

阅读更多信息https://developers.google.com/web/updates/2017/11/dynamic-import

AJAX加载

您可以使用AJAX调用加载一个额外的脚本,然后使用eval来运行它。这是最简单的方法,但由于JavaScript沙盒安全模型,它仅限于您的域。使用eval还打开了漏洞、黑客和安全问题的大门。

Fetch 加载

与动态导入一样,您可以通过fetch调用加载一个或多个脚本,使用fetch Inject库控制脚本依赖项的执行顺序:

fetchInject([
  'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})

jQuery加载

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

$.getScript("script.js", function() {
   
});

动态脚本加载

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

脚本甚至可以驻留在不同的服务器上。此外,浏览器会评估代码。<script>标记可以插入网页<head>,也可以在结束标记之前插入。

下面是一个如何工作的示例:

function dynamicallyLoadScript(url) {
    var script = document.createElement("script");  // create a script DOM node
    script.src = url;  // set its 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)
}

此函数将在页面的head部分的末尾添加一个新的<script>标记,其中src属性被设置为作为第一个参数提供给函数的URL。

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

检测脚本何时执行

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

这意味着,如果您直接使用这些技巧,您将无法在请求加载新加载的代码后的下一行使用它,因为它仍将加载。

例如:script.js包含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

然后按F5重新加载页面。而且有效!令人困惑

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

function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.head;
    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);
}

 

 

mob
关注 私信
文章
61
关注
0
粉丝
0