Search code examples
javascriptpageload

How to ensure a certain script tag remains at the top of <head>


I am working on a large website with a lot of existing third-party products already set up on it. I want to add a cookie consent script, which needs to be the first script executed. So I have added it at the top of <head> and when I do View Source I can see it is there at the top.

<head>
  <script src="https://path/to/cookie/consent/stuff/cookie_script.js"> 
  ... 

And then further down various other external libraries and frameworks are loaded: jQuery, GoogleAds, Hotjar and so on

    ...
          <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
          <script type="text/javascript" async="async" src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
       ...
</head>

But by the time the page has finished loading, when I inspect the DOM using the Web Dev Tools, I can see that my cookie script is no longer the first element in the <head>. Some other elements have been inserted in front of it.

    <head>
    <script src="https://www.googletagservices.com/activeview/js/current/osd.js?cb=%2Fr20100101"></script>
<script type="text/javascript" async="" src="https://www.google-analytics.com/analytics.js"></script>
<script src="https://securepubads.g.doubleclick.net/pagead/js/rum.js"></script>
    ...
    // Cookie consent script has been pushed down to here
      <script src="https://path/to/cookie/consent/stuff/cookie_script.js">
    ...
    </head>

What can I do about this?


Solution

  • These elements are inserted AFTER the page is loaded from your server, this means that by the time that these scripts are loaded and executed, your script have already run.