Remove duplicate JavaScript and CSS

How to Remove duplicate JavaScript and CSS

Method Type:  User (.JS/.CSS)
(This means that the method is handled by the user)


Status: Must be applied by the user.




Duplicated scripts hurt the performance by executing the same content more than once.


How duplicated scripts affect the website:


Different web browsers handle multiple instances of the same script on one page differently. Firefox is the only browser that downloads the script as many times as it is present on the page unless it is specifically cacheable. However all browsers cannot deal accordingly with the execution of the script and do it as many times as it exist. Sometimes more than one instance of the script is available on the same page because there is a widget that has added the script more than once (for example Google Ads scripts can also be loaded multiple times (gpt.js being a 45K script can really hurt performance if executed more than once).


Removing duplicated JavaScript and CSS provides the following Advantages:


Improved loading speed
Removed redundancies
Reduced page size



You can remove duplicated JavaScript and CSS from your website with the following code modifications:

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


You can do the same in PHP by creating a function called incertScript:


<?php insertScript("yourscript.js") ?>


Additionally, many widget developers have started using the line:


if(d.getElementById(id)) {return;} 


Which means that, if the async SCRIPT element already exist, the script will not be executed again. This is done by giving the SCRIPT element an ID, and checking for that ID on subsequent calls. Using this line is making sure that even if you see multiple script instances on your page only 1 of them is being executed.