Talking about the Design and Implementation of Hybrid Technology

http://www.cnblogs.com/yexiaochai/p/4921635.html

Preface

With the rise of the mobile wave, various APPs emerge in an endless stream. The rapid business expansion increases the team’s requirements for development efficiency. At this time, the cost of developing an APP using IOS&Andriod seems a bit too high , And H5’s low-cost, high-efficiency, and cross-platform features were immediately used to form a new development model: Hybrid APP.

As a mixed development mode, Hybrid The bottom layer of the APP relies on the container (UIWebview) provided by Native. The upper layer uses Html&Css&JS for business development. The bottom layer is transparent and the upper layer is diversified. This scenario is very conducive to front-end intervention and is very suitable for rapid business iteration, so Hybrid is popular.

I originally thought that this development model All know, then Hybrid has no value for discussion, but what surprised me is that there are still many people who are unfamiliar with Hybrid model. This situation is very common in second-tier cities, so I am trying to focus on it from another aspect. I would like to introduce Hybrid to you, and I hope it will be helpful for you to choose the correct technology.

Hybrid’s family history

Initially Ctrip’s applications are all Native , H5 site only accounts for a small part of its traffic. At that time, Native had 200 people booming, while H5 opened only about 5 people playing soy sauce. Behind the wireless team came a very strong server-side leader. In order to understand the front-end development, he actually used jQuery Mobile to develop the first version of the program. Although the plan was quickly overturned, the H5 team began to work hard and has caught up with Native’s business progress in a short period of time:

Suddenly a colleague from Andriod came over and told us that there is a method maximum tree limit in Andriod, and maybe some pages require us to embed H5 pages, so Native and the H5 framework team took the lead in doing the first Hybrid project. There was a situation where a set of codes was compatible with three terminals at a time. This development efficiency leveraged, the team tasted the sweetness, so the follow-up channels basically started Hybrid development. By the time I left, the whole mechanism was very mature, and there were hundreds of people on the front end.

Scene reproduction

The wolf factory has three big traffic apps, mobile phones When Baidu, Baidu Maps, and Nuomi APP recently connected to Nuomi, they found that they are also doing hybrid platform-related promotion, packaging static resources into Native. Native provides the ability to call native applications with js, from productization and engineering. It is very good, but there are two flaws:

① When all resources are packaged into Naive, the size of the APP will increase. can’t be avoided even with an incremental mechanismThe expansion of APP, because there are fewer channels now connected to a channel 500K, there is no feeling, once the platform becomes a platform, the size of the main APP will increase sharply

② The Nuomi front-end framework team encapsulates the capabilities of the Native side, but does not provide a supporting front-end framework. This solution is Incomplete. Many businesses already have H5 sites, and a separate program must be developed in order to access; and even for new business access, they will face the restriction that embedded resources must be static resources, and the projects that are made do not have SEO, if you pay attention to SEO It still needs to be re-developed, which is problematic from an engineering point of view.

But from the product accessibility and product In terms of chemistry, the general direction of Nuomi’s hybridization is very optimistic, and it has indeed achieved some results. In a short period of time, many channels have been connected. As the promotion proceeds, a large-scale Hybrid platform may be formed next year. But because I have also experienced the promotion framework, when I heard them fooling me that the performance will increase by 70%, which is basically the same as the Native experience, I don’t know why I laughed…

Summary

If you read the above stories and you still don’t know why you want to use Hybrid technology, I Here is another summary:

Hybrid development efficiency is high and cross-platform , From the perspective of business development, the underlying Hybrid has no version issues, and bugs can be fixed in time

Hybrid has its shortcomings, and the Hybrid experience is definitely not as good as Native, so it has its own use case, but for it needs quick trial and error, fast For teams that quickly occupy the market, Hybrid must be the best choice. After the team survives, they still need to build native apps with a better experience.

Okay, there’s so much to do with it The purpose of today is actually to introduce you to some design knowledge of Hybrid. If you read this article carefully, it may be helpful to you in the following aspects:

① What are the respective tasks of Native and front-end in Hybrid

②How to design the interactive interface of Hybrid

③ How to design Hybrid Header

④ How to design the directory structure of Hybrid and how to realize the incremental mechanism

Resource caching strategy, white screen problem… …

The article is some of my personal development experience, I hope it will be useful to you, and I hope you allA lot of support for discussion, point out the textinsufficientand some of your suggestions span>recommendation.

The Andriod related code in the article was provided by my colleague Mingyue. I am very grateful to Mingyue for supporting me. Scan the QR code here to download the APP for testing:

Andriod APP QR code:

Code address: p>

https://github.com/ yexiaochai/hybrid

Native and front-end division of labor

Before doing the hybrid architecture design, it is necessary to distinguish the boundary between Native and front-end. First of all, Native provides A host environment, to make reasonable use of the capabilities provided by Native, to achieve a general Hybrid platform architecture, from the front-end perspective, I think the following core design issues need to be considered.

Interaction Design

Hybrid architecture design is the first to consider The problem is how to design the interaction with the front-end. If this design is not good, it will have a profound impact on subsequent development and maintenance of the front-end framework, and this impact is often irreversible. Therefore, the front-end must cooperate with Native to provide universal Interface, such as:

① NativeUI component, header Components, message components

② Address book, System and equipment information reading interface

③ H5 Jump to each other with Native, such as how H5 jumps to a Native page, and how H5 opens a new Webview to make animation jump to another H5 page

Resource access mechanism

Native first needs to consider how to access H5 resources, so that it can access Native internal resources by file and online by URL Resources; it is necessary to provide an incremental replacement mechanism for front-end resources to get rid of the iterative release of APP and prevent users from upgrading APP. This will involve the storage strategy of static resources in the APP, the design of the update strategy, and the server-side support if it is complicated.

account information design

The account system is important and cannot be avoided , Native needs to design a good and secure identity verification mechanism to ensure that this is sufficiently transparent for business developers to open up account information.

Hybrid development and debugging

The function design is not the end, Native We need to discuss with the front-end a set of models that can be developed and debugged, otherwise many business development work will be difficult to continue. Many articles have already been accepted, so I won’t go into details in this article.

As for some communication designs that Native will pay attention to , Concurrency design, exception handling, log monitoring, and security module are not paid attention to because it is not the field I involve (in fact, I want to pay attention to it). What the front end has to do is to encapsulate Native The overall structure of the various capabilities provided is as follows:

Real business During development, Native will also encapsulate important modules such as payment in addition to the login module, which depends on the business.

Hybrid interactive design

Hybrid interaction is nothing more than Native calling the JS method of the front-end page, or the front-end page calling the interface provided by Native through JS , The bridge between the two is Webview:

The app itself can customize the url schema, and register the customized url in the dispatch center, for example

  • ctrip://wireless Open the Ctrip App
  • weixin:// open WeChat

< p style="line-height:1.5; margin:10px auto; font-family:verdana,Arial,Helvetica,sans-serif; font-size:14px"> Our communication between JS and Native is generally to create this kind of URL to be captured by Native Processing, other front-end calls to Native have also appeared in the follow-up, but the underlying encapsulation can be done to make it transparent, so the focus is on how to design the interaction between the front-end and Native.

JS to Native

Native will provide some APIs in each version, and a corresponding framework team will encapsulate them on the front end to release business interfaces. For example, Nuomi’s external interface looks like this:

copy code
1  BNJS.http.get();//Get the request data from the business server [1.0] The 1.3 version interface has extensions2 BNJS.http.post ();//Submit data to the business server [1.0]3 BNJS.http.sign() ;//Calculate signature [1.0]4 BNJS.http.getNA();//to NA The server takes the request data [1.0] The 1.3 version interface has extensions5 BNJS.http.postNA(); //Submit data to NA server [1.0]6 BNJS.http.getCatgData();// Obtain filtered data from Native【 1.1]
copy code

copy code
 1 BNJSReady(function(){ 2  BNJS.http.post({ 3 url:'http://cp01-testing-tuan02 .cp01.baidu.com:8087/naserver/user/feedback', 4  params: { 5 msg:'Test post', 6 contact: '18721687903' 7  },< /span> 8 onSuccess: function(res){ 9 alert('Send the post request successfully! ');10  },11 onFail: function(res){12 alert('Failed to send post request!'); 13  }14  });15 });
copy code

The front-end framework defines a global variable BNJS as the object that Native interacts with the front-end. As long as the JS library provided by Nuomi is introduced, and the Webview encapsulated by Nuomi In the container, the front end has gained the ability to call Native. I guess that Nuomi’s design is because it is easy to access and use by third-party teams. Mobile Baidu has a light application framework that also takes this route:

clouda.mbaas.account //The clouda global variables are released

This has a premise that Native itself is already very stable and rarely new The function is increased, otherwise you will face an embarrassment in the case of direct connection, because the web site is always up-to-date, and the native capabilities that are not provided will be called in some low-version containers and an error will be reported.

API-style interaction

We have no way of knowing how to do the bottom layer of Shoubai and Nuomi, but we found that the way to call the Native API interface is very similar to the interface provided by us using AJAX to call the server side:

The interface of a similar meager open platform is defined as follows:

< tr>

fan service (novice access guide)
read interface Receive news Receive user private messages, follow, unfollow, @ and other message interfaces
write interface Send message Reply to the user’s private message interface
Generate a QR code with parameters Generate a QR code interface with parameters

All we have to do is to create an ajax request in one way:

https://api.weibo.com/2/statuses/public_timeline.json

So when I actually design the Hybrid interaction model, I design the interface as a unit. For example, the overall interaction for obtaining the address book is :

Format Convention

The first step of the interaction is to design the data format, which is divided into request data format and response data format , The request model of reference ajax is probably:

$.ajax(options) ⇒ XMLHttpRequesttype (default: "GET") HTTP request method ("GET", "POST", or other). url (default: current url) The requested url address. data (default: none) The data contained in the request. For a GET request, this is the URL address containing the query string. If it contains an object, $.param will convert it into a string. 

So The request model that I agreed with Native here is:

copy Code
requestHybrid({ //Create a A new webview dialog window tagname:'hybridapi', //request parameters, which will be used by Native param: {}, // The method of calling back the front end after Native processing is successful callback: function (data) {}});
复制代码 < /div>

这个方法执行会形成一个URL,比如:

hybridschema://hybridapi?callback=hybrid_1446276509894&param=%7B%22data1%22%3A1%2C%22data2%22%3A2%7D

这里提一点,APP安装后会在手机上注册一个schema,比如淘宝是taobao://,Native会有一个进程监控Webview发出的所有schema://请求,然后分发到“控制器”hybridapi处理程序,Native控制器处理时会需要param提供的参数(encode过),处理结束后将携带数据获取Webview window对象中的callback(hybrid_1446276509894)调用之

数据返回的格式约定是:

{  data: {},  errno: 0,  msg: "success"}

真实的数据在data对象中,如果errno不为0的话,便需要提示msg,这里举个例子如果错误码1代表该接口需要升级app才能使用的话:

{  data: {},  errno: 1,  msg: "APP版本过低,请升级APP版本"}

代码实现

这里给一个简单的代码实现,真实代码在APP中会有所变化:

复制代码
 1 window.Hybrid = wind ow.Hybrid || {}; 2 var bridgePostMsg = function (url) { 3     if ($.os.ios) { 4         window.location = url; 5     } else { 6         var ifr = $('