March 14, 2012

javascript: add script that will be evaluated before body scripts?

Question by IttayD

I have a script foo.js that is included in <head>. Inside body I have an inline script. Inside it, I want to add to the document another script for bar.js that will be loaded and evaluated before the inline script.

<html>
  <head>
    <script src="foo.js" type="text/javascript"/>
  </head>
  <body>
    <script type="text/javascript">
      bar()
    </script>
  </body>
</html>

In foo.js I want to add a script pointing to bar.js

bar.js:

function bar() {
  alert('hi');
} 

What should be the code of foo.js?

NOTE: I know I can use onload in this trivial example. But in my real case, bar.js contains a function that is called several times and I want to be able to inline these calls in the right sections of the page (for code locality)

Answer by Rob W

You have got two options:

  1. Use document.write('<script src="bar.js"></script>') in foo.js.
  2. Dynamically create and insert a <script> element within the head (since scripts in the head have to be loaded before the rest is parsed, this works):

    !function(){
        var s = document.createElement('script'),
            currentScript = document.getElementsByTagName('script')[0];
        s.src = "bar.js";
        currentScript.parentNode.insertBefore(s, currentScript);
    }()
    

Answer by Starx

As you are doing currently, the script of the head will be evaluated at first and then the one from the body.

But when the script of head is loaded, the script inside the body will not have been loaded yet. SO the function will be unavailable to it.

So you best way I know is to use window.onload which triggers the code once every DOM elements like script are ready for manipulation.

window.onload = function() {
   bar();
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!