Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in performance and memory footprint between referencing a Javascript using src or directly injecting it in the HEAD

What are the differences in performance and memory footprint , if any, in these different approaches:

1. Using Src

<script type='text/javascript" src="1MBOfjavascript.js"></script> 

2. Directly injecting in the Head

$('head').append("<script type='text/javascript'>1MBOfJavascriptCode</script>");

I'm interested because we are developing a Cordova App where we use the second method to Inject to the DOM a previously downloaded Javascript bundle read from the HTML Local Storage.

Given that the script will probably grow in size, I'd like to know if with the second method I could incur in some memory issues or other DOM problem.

like image 519
systempuntoout Avatar asked Apr 27 '15 10:04

systempuntoout


2 Answers

I believe the overhead in such cases should be insignificant as the main processing/memory consumption is based on how the actual script works. Ie the memory used by file would be the total size of the script which is what 1MB at max? However during execution the same script can use up 100MB easily.

Anyways , coming to the point.

Plain text inclusion would be better if it has to be included in all cases as it skips a script execution and also does not cause re-rendering by browser after the append. Append option should be used in cases where you only need the script under specific conditions on client side and do not load it un-necessarily.

like image 123
arkoak Avatar answered Nov 19 '22 22:11

arkoak


The browser goes through all elements before to render the page so I would imagine it is exactly the same, if anything if you had scripts after the page is downloaded chances are that you will get errors of the type "call to undefined functions" if you call onto a function that you have added after the load. My advise would be add them at load using src but keep things tidy.

like image 24
user1620090 Avatar answered Nov 19 '22 22:11

user1620090