Autoloading Javascript

给你一囗甜甜゛ 提交于 2019-12-04 10:22:47

Have you consider using requirejs and probably Lazy loading.

http://www.joezimjs.com/javascript/lazy-loading-javascript-with-requirejs/

Here is sample version:

  1. You can download here.

  2. The sample is based on this folder structure :

    public

    • index.html
    • scripts

      • app.js
      • lib

        ** jquery-1.10.2.js

        ** require.js

3 . From Code:

html

`<!DOCTYPE html><html>
 <head><title>Sample Test</title>`

<script src="scripts/lib/require.js"></script> <!-- downloaded from link provide above--> <script src="scripts/app.js"></script></head>

`<body><h1>My Sample Project</h1><div id="someDiv"></div></body></html>`

application configuration app.js

requirejs.config({
    baseUrl: 'scripts',

    paths: {
        app: 'app',
        jquery: 'lib/jquery-1.10.2' //your libraries/modules definitions
    }
});

// Start the main app logic. loading jquery module
require(['jquery'], function ($) {
        $(document).on('ready',function(){
            $('#someDiv').html('Hello World');
        });
 });

jQuery-only option

If you are looking for a jQuery-only solution, have a look at jQuery.getScript(). It would be a great candidate for handling the script loading portion of your problem. You could then write a very small wrapper around it to load all the scripts—something like you wrote above:

var loadScripts = function(scripts) {
  $.each(scripts, function(name, path) {
    jQuery.getScript("/root/path/" + path + ".js");
  })
}

If you are interested in more information on this approach, read this article by David Walsh.

Other great libraries

I strongly recommend taking a look at the current batch of script-loading libraries. I think that you will pleasantly surprised by what is out there. Plus, they come with the benefit of great community support and documentation. RequireJS seems to be the front runner but David Walsh has great articles on curl.js and LABjs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!