Home > Web Front-end > JS Tutorial > body text

JavaScript dynamic loading implementation method 1_javascript skills

WBOY
Release: 2016-05-16 17:50:31
Original
1394 people have browsed it

There are also many JS dynamic loading frameworks, such as In.js. But this is not the way I want to write it, so let me tell you what I think.

First come a piece of java code

Copy the code The code is as follows:

import Biz.User;
User u = new User();
u.show();

The process is package import, instantiation, and calling.

JS cannot be used to import packages, or in the code sense, it is generally just the introduction of script tags on the page.
Then suppose you need to write it like this
Copy the code The code is as follows:

Using(" User");
var u = new User();
u.show();

So, can it be implemented in JS?

Let’s analyze it sentence by sentence. Of course, the premise is that the page does not load user.js with the script tag, otherwise it will be meaningless.

The first sentence

Using("User");

Why use Using? Of course it is just my naming idea. You can think of C# and use using , just borrowed.

What is written in Using is of course the object I need, User. As the name suggests, of course I wrote Using("User"). Let’s not talk about how it is implemented inside, at least this is the idea.
Because I can’t simulate the keyword by writing Using User; at least I can’t do this.
The second and third sentences
Copy code The code is as follows:

var u = new User();
u.show();

It’s normal, just ordinary instantiation and function calling. The only thing that puzzles me is where does the User object come from? Then of course it is imported when importing the package in the first sentence.


The process is just such a process, so the key to whether it can be realized lies in the first sentence. In other words, whether the package can be successfully guided, and how to guide the package.

Draw inspiration from script tags, yes, asynchronously load the required js files.
That is to say
Copy code The code is as follows:

Using("User") ;

is equivalent to writing a sentence
Copy the code The code is as follows:


Looking at it now, does it make sense to do this? Just to write the script tag as JS and dynamically introduce it? Or, just to save a few characters?

Of course not, it’s pointless! So what should we do?
Let’s start with efficiency.
If a page needs to load N multiple js files, as follows
Copy the code The code is as follows:









Blah blah blah.

Isn’t it scary? It is quite scary, and the cost of post-maintenance is very high. How many pages there are, you may need to modify a few pages. So, what if the page only introduces a few key js files and all other files are dynamically loaded?
For example, we only need to load the jquery file, and then call
Copy code The code is as follows:

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

In this way, we only need to introduce
Copy code The code is as follows:



That’s it.
So what are the disadvantages of this way of writing? Look at a piece of code
Copy the code The code is as follows:

$.getScript("user.js" ,function(){
$.getScript("order.js",function(){
$.getScript("type.js",function(){
$.getScript("validate.js ",function(){
// and so on..
});
});
});
});

PS : This situation can be avoided by using the watch function of In.js. This is beyond the scope of this blog post.

Is it an eyesore? Are you still willing to align your code? Even with formatting tools, would you still want to match the closing bracket to which $.getScript it corresponds to? Of course not.
Then, the java-like guide package form comes out.
Copy code The code is as follows:

Using("User");
Using( "Order");
Using("Type");
Using("Validate");
// and so on..

Or if you want, you can
Copy code The code is as follows:

Using("User","Type","Order ","Validate",...);

The writing problem doesn't matter. Of course I recommend using the first method, clear.

After importing the package, all usages do not require any nesting and can be used normally.
Copy code The code is as follows:

var u = new User();
var o = new Order();
// and so on..

But a question will be raised. If asynchronous loading is executed during Using("XXX"), then
Copy code The code is as follows:

Using("User");
Using("Order");
Using("Type");
Using("Validate");
// and so on ..

In this section, I need to load 4 files asynchronously. Although it is asynchronous, it is a bit troublesome? And 4 links need to be created. If you are willing to merge JS, you can. Moreover, I don’t need to use objects when using. Is this a waste of resources?

As for this problem, my solution is to learn hibernate, lazy loading, and on-demand loading.
So how to do it?
Copy code The code is as follows:

Using("User");

It is definitely not loading at this time. What should I do if it is not loading? Of course, it returns a mock, which is a simulation object. Let the user use it first, and only when the user really needs to use this object, load the required js. That is to say
Copy code The code is as follows:

Using("User"); // After this sentence is executed, a User object will be created, which is just a mock at that time
var u = new User(); // At this time, what is needed is the real User object instance, and it is at this time to dynamically load the JS file , and returns the instantiated User object

As we all know, asynchronous loading does not conflict with the current running state, that is to say
Copy code The code is as follows:

var u = new User();

이 문장이 실행된 후에는 u는 실제 의미도 없고 그 이상도 없는 변수입니다. 그래서 이 문제를 해결하는 방법은, 당분간 제가 생각할 수 있는 유일한 방법은 동기화 전략을 사용하는 것 뿐입니다. js가 로드될 때만 후속 js 문이 실행되는 점은 다소 아쉽고, 동기화로 인해 발생할 수 있는 브라우저 정지 문제도 당분간은 무시하도록 하겠습니다. 앞으로 더 나은 솔루션.

그렇다면 이렇게 동기화하면 어떤 이점이 있을까요?라는 질문이 생깁니다.
적어도 비동기 로딩에 비하면 단점은 없을 것 같아요. 예를 들어 일반적인 비동기 로딩은
코드 복사 코드는

$입니다. getScript("user .js",function(){
var u = new User();
})

이 명령문을 실행하면 함수가 실행됩니다. js는 로드될 때까지 실행되지 않습니다. 그런 다음
복사 코드 를 비교하면 다음과 같습니다. :

var u = new User();

이론적으로 user.js가 로드된 후에 모두 실행되므로 시간은 동일해야 합니다.

적어도 두 번째 코드는 Java 스타일 코드와 더 유사하므로 비즈니스와 관련되지 않은 다른 코드는 신경쓰지 마세요.

그럼 필요한 객체가 어디에 있는지, 어떻게 로드하는지 어떻게 알 수 있나요? 내가 생각할 수 있는 것은 구성 파일을 시뮬레이션하는 것뿐입니다. In.js와 같은 추가 기능이나 다른 프레임워크의 등록 기능을 사용하는 대신 구성 파일을 사용하는 이유는 무엇일까요? Java이며 나중에 수정될 수도 있습니다.
코드 복사 코드는 다음과 같습니다.

Using.Config = {
" User" : "/js/user" // JS 파일을 로드해야 하기 때문에 .js를 숨길 수 있습니다
}

전체 아이디어는 대략 이렇고 몇 가지 제약을 두었습니다. 예를 들어
코드를 추가한 후 코드는 다음과 같습니다.

var u = new Using.Modules .User();

이를 통해 일부 전역 변수를 줄일 수 있으며, 필요한 경우 모든 개체가 가질 수 있는 일부 공통성을 삽입하여 생성 시 반복되는 코딩을 줄일 수 있습니다. 수업.

물론 네임스페이스를 사용하지 않는 것도 여전히 지원됩니다.

이 제약의 실효성을 해결하기 위해 Class.create 함수를 추가하여 클래스 제약을 생성합니다.
코드 복사 코드는 다음과 같습니다.

Using.Class.create("User" ,function( ){
}).property({
}).static({
}).namespace(Using.Modules);

여기서 일반적인 의미는 다음과 같습니다.

create(클래스 이름, 생성자)
property(클래스의 속성)
static(클래스의 정적 속성)
namespace(네임스페이스)

이에 대한 확장 , MVC 양식을 추가하면 어떨까요?
나중에 MVC를 원하면 여러 클래스 간의 동적 유지 관리가 필요하거나 생성 시 Using 클래스에 의한 자동 유지 관리가 필요하다는 것을 알았습니다. 아직 좋은 해결책을 생각하지 못했습니다. , 그래서 저는 가입하지 않았습니다.

위의 텍스트를 통해 마침내 Using.js를 얻고
만 하면 됩니다. 페이지에
코드 복사 코드는 다음과 같습니다.
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!