简体   繁体   中英

Inline Javascript: Is it a good practice?

I have many view templates where i have inline javascript specific to that view.

for eg:

app/views/something/index.html.haml
.some-id
  %h4 Something

#this javascript is not reused anywhere. Used only in this view
:javascript
  $(document).ready(function() {
    $('.some-id').addClass('something')
  })

Is it a good practice to have the views like above?

It is definitely a pain to maintain inline javascript across multiple views. So i started moving them slowly into one single javascript file. But i am not sure if that's a good thing because, all the javascript will now get executed for all the pages.

So which is the best place to put view specific javascript?

If you are worried about page load time, you should use something like loadjs . It is just not maintainable to be place JS in your views like that. For super simple projects then maybe, but in general you should stay away from it.

Another thing to note is that browsers will cache your javascript when it is loaded from a file. They cannot do this when it is inline because the HTML is rendered every page load. So you probably are looking at an overall performance loss when doing it inline, even without loadjs.

Typically, my thoughts on the matter...

As far as appearance and useability goes: If it is possible to reuse code in multiple spots then it should be regrouped as a function. This function can be called and reduce your lines of code in your documents. This will increase efficiency in time taken to write code, it also will make your end result much neater and easier to maintain.

As far as efficiency goes with loading the page: I do not think that you should be calling all of the javascript includes every time the page loads. Instead of putting everything that you want to reuse in functions into another document consider grouping some of it in the head of the document. Essentially it is not different as just doing a javascript include, however if you are using that one large javascript file as a library for all pages that you have on your website then you can cut some of that code down by just putting what functions you need in the head of the documents.

edit: To answer your question more directly, i believe it is common belief that inline javascript is always a bad practice.

I am not one who always believes this to be true. I will say when maintaining other's code i do not mind if they use inline, external files, or locate it in the head as long as they are just consistent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM