1. javascript include
Javascript does not include statements. In particular, there is dependency between scripts. You cannot dynamically control the loading of scripts. In general, the simplest include statement is basically like this, of course, jQuery is used for the request script.
Copy codeThe Code is as follows:
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 });
$ ('Head'). append (js );
// $. GetScript (jsurl );
}
Basic usage
It should be noted that the function is actually sending GET requests by jQuery. ajax getScript (), but after GET processing and $. getScript () is different, so the usage method is different. getScript () generally needs to write the Dependent Function to its callback function, for example:
$. GetScript ('some. js', function (){
// Write tasks that depend on some. js files.
});
The include here does not need to be written in this way, but directly:
Include ('some. js ');
// You can directly write functions defined in some. js files.
Enable Cache
The other is about file caching. By default, $. getScript adds a timestamp after the url so that the browser is not allowed to read the cached file during the second request. If we getScript ("some. js "), and finally GET some in the request. js? _ 23432434534235 and so on. This is a policy that forces no caching. It is better in the development stage. However, in the production stage, the user's browser will not cache our js scripts every time, this has a great impact on efficiency. We should add a version stamp after the js script, such as some. js? V = 1, instead of the timestamp that changes every time, you need to use:
$. AjaxSetup ({cache: true });
This will disable jQuery's automatic timestamp feature after the url.
RequireJs
If a large number of scripts are dependent on each other and you need to dynamically decide which scripts to load, I recommend using requirejs.
Its basic usage is:
Require (["some/module", "a. js", "B. js"], function (someModule ){
// Do something
});
One of its requirements is that your front-end js is developed as a modular model. If the front-end logic is complicated, it should be a good choice to use modular modules for front-end development, I will talk about JS modular development in future articles. Here I will just give a brief introduction. If you are interested in this aspect, go to the requireJs official website.