Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to output script tags in the middle of the page?

Tags:

jquery

Merely out of convenience, I'm hoping to, using a server side language, just output a simple <script> tag with jquery's document.ready() function. Is this considered bad practice? I know some people consider inline javascript bad practice, which makes me wonder about this.

like image 371
Matthew Avatar asked Nov 05 '10 17:11

Matthew


People also ask

Where is the best place to put script tags?

The script tag should always be used before the body close or at the bottom in HTML file. The Page will load with HTML and CSS and later JavaScript will load.

Does position of script tag matter?

Yes, it does affect the performance of the webpage loading. The problem is, normal <script> tags are blocking so everything after the script tag has to wait till the script tag is done loading and parsing before the rest of the page can load.

Where is the best place to put your script tags if you don't want them to slow the loading of the main page content?

The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.

Can you put script tags anywhere?

The “script” tagJavaScript programs can be inserted almost anywhere into an HTML document using the <script> tag.


1 Answers

It's not a problem from the technical point of view, because document.ready() will fire only after the DOM is fully parsed.

I wouldn't consider it good style, though. It can make maintenance hellishly difficult, because you can't see what's happening on document load at one glance any more.

I would aim to keep everything in one document.ready() block if at all possible, and that block in the head or even an external script file if at all possible.

like image 87
Pekka Avatar answered Nov 15 '22 04:11

Pekka