Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defer inline javascript execution? [duplicate]

In my website I have many inline javascript snippets. Most of them require jquery and similar stuff.

But I would like to defer jquery load to after the page was rendered. And that means, that my inline javascript would execute, before jquery was loaded. Is there anything I can do about it? I am looking for easy to implement solutions (I also cannot move my inline javascript since it is automatically generated while page is being prepared for the user).

like image 461
ojek Avatar asked Nov 24 '13 20:11

ojek


People also ask

Can you defer inline JavaScript?

Inline JavaScript executes in the order in which it appears in the page. There's no “deferring” it. As a result, if something in there relies on jQuery, it'll simply throw an error to the console log and refuse to execute.

Do deferred scripts run in order?

Scripts with the defer attribute will execute in the order in which they appear in the document. This attribute allows the elimination of parser-blocking JavaScript where the browser would have to load and evaluate scripts before continuing to parse.

What happens when you defer JavaScript?

The defer attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM. The script loads “in the background”, and then runs when the DOM is fully built.

Should I use defer in JavaScript?

You should use defer for all other scripts. defer is great because it: Gets loaded as soon as possible — so it reduces load times. Doesn't execute until everything you need is ready — so all the DOM you need is there.


1 Answers

It would be much better if you could place your javascript at the end of the document. Sprinkling your source with small inline javascript snippets is a killer on page performance.

That said, you could create an array and push functions on this array. Then, at the end of your page, right after you load jquery, loop over the array and execute each function.

E.g.:

<html>
  ...
  <script>window.loadEvents = [];</script>
  ...
  <script>loadEvents.push(function() { alert("inline code here"); });</script>
  ...
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>$.each(loadEvents, function(_,f) { f(); });</script>
</html>

However - as I said - it would be better to just push all the script elements into the bottom of the page, instead of switching back and forth between html and javascript. The rendering performance will be severely degraded, if you do this.

like image 159
troelskn Avatar answered Sep 30 '22 16:09

troelskn