0

I have couple of CDN files what I call in header

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/scriptaculous/1.8.2/scriptaculous.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

and after all my js files what are depending on this libraries, but google's page speed complains that those scripts are blockers on page load. So I tried to put everything before body closing but in this case I will have all scripts broken because they depend on jquery.

I tried to use defer but like that the same problem as in footer. How do I load async javascript libraries to not break the hole?

fefe
  • 8,755
  • 27
  • 104
  • 180

3 Answers3

2

General solution is to use async module load like RequireJS. Here's a jQuery integration case: http://requirejs.org/docs/jquery.html

Considering "but in this case I will have all scripts broken because they depend on jquery." you could add check in your JS code like:

$(document).ready(function(){
  //your jQuery-based code
})


//if jQuery loading failed
if(!window.jQuery){

}
shershen
  • 9,875
  • 11
  • 39
  • 60
  • there are a lot of scripts included I just want to optimize the page load not to refactor the hole code – fefe Jun 07 '16 at 12:48
  • i've listed to ways - refactor with AMD or quick patch with ```!window.jQuery```. – shershen Jun 07 '16 at 12:53
0

You might want to have a look at the number of files from the same host. Look at this.

Community
  • 1
  • 1
EinarI
  • 627
  • 1
  • 9
  • 14
0

What you would like to achieve is AMD (Asynchronous Module Definition)

Asynchronous module definition (AMD) is a JavaScript specification that defines an API for defining code modules and their dependencies, and loading them asynchronously if desired. Read more: https://en.wikipedia.org/wiki/Asynchronous_module_definition

There are a bunch of frameworks for that:

Or you can load JS files manually, using this method (not recommended): https://stackoverflow.com/a/7719185/1502230

Community
  • 1
  • 1
Andras Szell
  • 527
  • 2
  • 13