Require.js与简单地创建< script>元素中的元素? [英] What's the difference between Require.js and simply creating a <script> element in the DOM?

查看:105
本文介绍了Require.js与简单地创建< script>元素中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Require.JS和仅在DOM中创建<script>元素有什么区别?

What's the difference between using Require.JS amd simply creating a <script> element in the DOM?

我对Require.JS的理解是,它提供了加载依赖项的能力,但这不能简单地通过创建一个加载必需的外部JS文件的<script>元素来完成吗?

My understanding of Require.JS is that it offers the ability to load dependencies, but can this not simply be done by creating a <script> element that loads the necessary external JS file?

例如,假设我具有功能doStuff(),该功能需要功能needMe(). doStuff()在外部文件do_stuff.js中,而needMe()在外部文件need_me.js中.

For example, lets assume I have the function doStuff(), which requires the function needMe(). doStuff() is in the external file do_stuff.js, while needMe() is in the external file need_me.js.

以Require.JS方式执行此操作:

define(['need_me'],function(){
    function doStuff(){
        //do some stuff
        needMe();
        //do some more stuff
    }
});

只需创建一个脚本元素即可完成此操作:

function doStuff(){
    var scriptElement  = document.createElement('script');
    scriptElement.src = 'need_me.js';
    scriptElement.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(scriptElement);

    //do some stuff
    needMe();
    //do some more stuff
}

这两种工作.但是,第二个版本不需要我加载所有Require.js库.我真的看不到任何功能上的差异...

Both of these work. However, the second version doesn't require me to load all of the Require.js library. I don't really see any functional difference...

推荐答案

这是ajaxian.com上有关如何使用它的漂亮文章:

Here is the nice article on ajaxian.com as to why use it:

RequireJS:异步JavaScript加载

  • 某种#include/import/require
  • 加载嵌套依赖项的能力
  • 易于开发人员使用,但随后得到了可帮助部署的优化工具的支持

这篇关于Require.js与简单地创建&lt; script&gt;元素中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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