Responsive javascript: Loading JS when needed

Source: Internet
Author: User
Tags format end interface

Article Introduction: compared to the previous loading of all JavaScript on the front end, why don't we load the least amount of JavaScript and then load the extra JavaScript code when the user interface needs it?

A year ago I made a speech on the subject. The first time I focused on this technology was because @dhh released some of the ideas they used in 37signals. I've noticed how they use JavaScript in the template view, dynamically generating JavaScript. This is its focus, which arouses my thinking.

Compared to the previous loading of all JavaScript on the front end, why don't we load the least amount of JavaScript and then load the extra JavaScript code when the user interface needs it?

I call this the response JavaScript, you've heard the term pjax, or unobtrusive JavaScript, and so on. The purpose is for the back-end JavaScript to be loaded by the front-end action. Whether it's get, POST, delete wait, as long as the request is Ajax, the response will be JavaScript rather than JSON.

Some examples of some of the products you use may already be using this concept. BCX, GitHub, Airbnb have used this concept in different ways. The problem with this concept is that it does not bind to any library or frame, and you must use the current tool to work on it. Thankfully, a JavaScript library is now available to help you get started. JQUERY-UJS allows you to add remote= "true" to any link that will automatically convert to an AJAX call.

First, an example

Class Postscontroller < Applicationcontroller
def index
@posts = Post.all
End

Def show
@post = Post.find params[:id].to_i
respond_to do format
Format.js
Format.html
End
End

DEF create
#.. Create a Post
respond_to do format
Format.js
Format.html
End
End
End



    <%= @posts. Each do post%>
    <%= Render_link_to_post (POST)%>
    <% End%>

# App/views/create.js.erb
(function () {
var $post = $ ("<%= J Render_link_to_post (@post)%>")
$post. Hide (). Prependto ($ ("ul.posts")). FadeIn ()
})()

# App/views/show.js.erb
(function () {
var $post = $ ("<%= J Render" ("Overview", Post: @post)%> ")
$post. Dialog ("Open")
})()



<%= @post. Title%>


<%= @post. Body%>

#helper. RB
def render_link_to_post (POST)
Link_to Post.title, Post_path (POST), remote:true
End

In this example, when someone clicks on the link, it will call/posts/:id. If the request is Ajax, it will call Show.js.erb and execute the code in the template. If not, it will call Show.html.erb. There is also a template called Created.js.erb that will be invoked when you create a resource through an AJAX form. The form is cleaned as simply as possible.

URL to help you navigate to the bug
Let's say you have a bug when clicking on a link, and by using this technique, you can trace the origin by looking at the URL.
For example: Posts/:id is associated with the JS template located in App/views/posts/show.js.erb.
As you would expect when you are working with HTML views.

Web page has a lifetime
Review the above example. When you publish a post with an AJAX form, a default list will generate a link to the post. Look at the request: it's the same as when you call/posts, it's not an accident. When you use this method, you try to avoid code duplication, and Ajax uses the same components as normal requests in addition to not eventually generating the page.

This means that when you post a new post, if you refresh the page, the same list of articles will appear, because they use the same mechanism.

Reusing the same view logic
This is a previous extension. Now that you've generated HTML on the server side, you might see a lot of duplicate code in the view, and using helper classes or modifiers to simplify the code won't be a difficult task.

Because all maps come from the same place, the modification of HTML can also be done in the same place. For example, if I wanted to replace the chain in the list with a more descriptive one, I could modify the implementation details of render_link_to_post (a bad function name, excuse me) to accommodate the change.

JavaScript transfer between actions & Page load optimization
Now, your JavaScript is loaded in 2 different places:

The JavaScript is loaded by a label link. Loaded on page load, runtime can not be customized, JavaScript can be precompiled;
Loads as a response to a user's page action.
Better control of the content of the service is the advantage of this approach. If you feel that the parsing code is more slow, you can load some of the requested loads into the tag link.

Load required when needed
Because the Web page is rendered on the server side, so you have a lot of optional libraries when the response is minimized, maybe you can try jquery, zepto, or something, but remember that JavaScript almost never (I don't know if it's all) does not render the page at load time and starts after loading.

Look at the example above. There's a problem with create.js.erb, I can wrap it with good features and other good things, but what's the point if people never post posts?

This requires you to maintain a balance. When there are some things that are used in large quantities (more than once per user per page), use tags like your other libraries to load it, and others load it when the HTML action is triggered.

Repeatable actions (for debugging purposes)
Have you ever been in a situation where 3~4 a different action prompts you for bugs in your JavaScript code when you debug your application? Because the response is a standalone JavaScript code, you can only paste the response into the console to catch the exception step by step.

What did I do, I took it off the block between me and I was using the obstacles between variables, so that in the console I can reduce bugs to variable levels.

Clear
The client's JavaScript is usually used in combination with notifications or events, triggering these events, receiving server updates, and all of this is instantly ready. Usually, instant results are often difficult to track.

The result is easy to understand when the response is JavaScript code. Looking at the above example, I'll detail you understand the expected behavior of these two AJAX responses.

That's it
This is my choice, you can also have your own choice. I hope you enjoy this article and have the urge to try it yourself.



Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.