adviner
adviner

Reputation: 3567

Is there a performance hit by loading javascript dynamically from the client

Take two scripts. One uses tag to load javascript:

<script src="/myscript.js" type="text/javascript"></script>

and tag for css:

<link rel='stylesheet' type='text/css' href='style.css'>

another method is to dynamically load it via javascript like:

fileRef = document.createElement('script');
fileRef.setAttribute('type', 'text/javascript');
fileRef.setAttribute('src', url);           

or for css dynamic loading:

fileRef = document.createElement('link');
fileRef.setAttribute('rel',  'stylesheet');
fileRef.setAttribute('type', 'text/css');
fileRef.setAttribute('href', url);

Ive seen other libraries (just cant think of the name) that loads your scripts dynamically. Aside from making sure that you dont load scripts that already has been loaded is there a performance hit for loading it dynamically from the client instead of just hard coding each file using and/or on the page (statically or in server side)?

Upvotes: 0

Views: 90

Answers (1)

Christian Landgren
Christian Landgren

Reputation: 13763

Yes. There is a difference and it has to do with the roundtrip time from server to client and back. Two statically defined scripts will load in parallel but if you have one file1.js that is dynamically loading a second file file2.js, file2 will be delayed 2*pingtime to your server. Also the web client will put the second request last in the request queue which means that if you have many images, stylesheets etc you might delay the initial startup time considerably.

Upvotes: 1

Related Questions