Simple analysis of Javascript using include and require

  • 2020-03-29 23:40:14
  • OfStack

1. The javascript include
Javascript does not include statements sometimes annoying, especially there is a dependency between scripts and scripts, you can not dynamically control the loading of scripts, generally speaking, the simplest include is basically this, of course, we use jQuery to request scripts.

  include: function (jsurl) {
        if (jsurl == null || typeof(jsurl) != 'string') return;
        var js = document.createElement('script');
        js.type = 'text/javascript';
        js.charset = 'utf-8';
        js.src = jsurl;
        $.ajaxSetup({ cache : true });

Basic usage

It should be noted that this function actually sends a GET request to jQuery. Ajax getScript(), but the processing after GET is different from $.getscript (), so the use method will be different. GetScript () generally needs to write dependent functions to its callback function, such as:

$. GetScript ('. Some js', function () {
      // do the writing that depends on some. Js file.

And our include doesn't have to be like this, it just says:

Include (' some. Js);

// here you can directly write a function that depends on the function defined in the file some.js

Open the cache

In addition, about file caching, by default, $.getscript will add a timestamp after the url, so that the browser will not read the cache file in the second request, if we getScript("some.js"), finally in the request will become GET some.js? _23432434534235 and so on, this is a kind of mandatory non-cache strategy, in the development phase is good, but in the production phase, will cause the user's browser every time not cache our js script, this is a big impact on efficiency, we should add their own version after the js script, such as some.js? V =1, instead of using a timestamp that changes every time, use:

$.ajaxsetup ({cache: true});

This turns off jQuery's ability to automatically add a timestamp to the url.


I recommend using requirejs if your scripts are heavily interdependent and need to dynamically determine which scripts to load.

Its basic usage is:

Require (["some/module", "a.module "," b.module "], function(someModule) {
      / / do something

It has a requirement is your front-end js as a module type development, on the front end logic is more complex, use the module type for the front-end development should be a kind of good choice, and modular development of js in the next article will discuss specifically, here only a brief introduction, if interested in this aspect can go to the website (link: and have a look.

Related articles: