IttayD
IttayD

Reputation: 29163

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

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)

Upvotes: 1

Views: 516

Answers (5)

whiteatom
whiteatom

Reputation: 1455

I'd use jQuery's ready function that will fire when all the dependancies have loaded...

$(document).ready(function () {
    bar();
});

Upvotes: 0

Starx
Starx

Reputation: 79069

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();
}

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

Let me get this straight... You're trying to include a script that will run before the script that includes it? That makes absolutely no sense.

The closest I can figure out is trying to run the included code immediately, before proceeding to further code in the current script block. That can be achieved by fetching the script to include via a synchronous (blocking) AJAX call and running it through eval. This is overall a bad idea and there should never be any need to do such a thing - just put the scr

Upvotes: 0

Rob W
Rob W

Reputation: 349262

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);
    }()
    

Upvotes: 3

beaumondo
beaumondo

Reputation: 4930

Can you not use the onload attribute to call the function you want first.

<body onload"bar()">

Upvotes: 0

Related Questions