4

I'm trying to load dynamically script with this code:

var headID = document.getElementsByTagName("head")[0]; 
var script = document.createElement('script'); 
script.type='text/javascript'; 
script.src="js/ordini/ImmOrd.js"; 
script.setAttribute("onload", "crtGridRicProd();");                       
headID.appendChild(script);

I need to launch crtGridRicPrdo() function when the page starts, and in FireFox all works fine but in Internet Explorer I have a problems!

3
  • Wich version of IE did you use?
    – Reporter
    Commented Jul 4, 2011 at 8:15
  • What problems you have with IE ? Is it an error message? Need more details. Commented Jul 4, 2011 at 8:16
  • IE 7 and no show error but not load function!
    – Marco
    Commented Jul 4, 2011 at 9:21

5 Answers 5

8

Internet explorer does not support "onload" on script tags, instead it offers the "onreadystatechange" (similarly to an xhr object). You can check its state in this way:

script.onreadystatechange = function () {
   if (this.readyState == 'complete' || this.readyState == 'loaded') {
     crtGridRicProd();
   }
};

otherwise you can call crtGridRicProd() at the end of your js file

EDIT

example:

test.js:

function test() {
    alert("hello world");
};

index.html:

<!DOCTYPE html>
<html>

  <head>
    <title>test</title>
</head>
<body>
    <script>
        var head = document.getElementsByTagName("head")[0] || document.body;
        var script = document.createElement("script");

        script.src = "test.js";

        script.onreadystatechange = function () {
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                test();
            }
        };

        script.onload = function() {
            test();
        };

        head.appendChild(script);

    </script>
</body>

you will see the alert in both browser!

4
  • i try with this but not works for me, also in Firefox now not work and withouts show error
    – Marco
    Commented Jul 4, 2011 at 9:09
  • i try but not work for me! how can replace this for IE: script.setAttribute("onload", "crtGridRicProd();"); ?? THANKS
    – Marco
    Commented Jul 4, 2011 at 11:55
  • I don't understand why are you still using setAttribute(), just attach the handlers like I showed in my example and obviously replace "test()" with "crtGridRicProd()"... it MUST work!
    – daveoncode
    Commented Jul 4, 2011 at 12:21
  • IE8 don't returns readyState == 'complete', but 'loaded'. Otherwise works fine, thanks
    – ijavid
    Commented Sep 28, 2013 at 4:09
5

I use the following to load scripts one after another (async=false):

var loadScript = function(scriptUrl, afterCallback) {
            var firstScriptElement = document.getElementsByTagName('script')[0]; 
    var scriptElement = document.createElement('script');
            scriptElement.type = 'text/javascript';
            scriptElement.async = false;
            scriptElement.src = scriptUrl;

    var ieLoadBugFix = function (scriptElement, callback) {
        if ( scriptElement.readyState == 'loaded' || scriptElement.readyState == 'complete' ) {
            callback();
        } else {
            setTimeout(function() { ieLoadBugFix(scriptElement, callback); }, 100);
        }
    }

    if ( typeof afterCallback === "function" ) {
        if ( typeof scriptElement.addEventListener !== "undefined" ) {
            scriptElement.addEventListener("load", afterCallback, false)
        } else {
            scriptElement.onreadystatechange = function(){
                scriptElement.onreadystatechange = null;
                ieLoadBugFix(scriptElement, afterCallback);
            }
        }
    }
    firstScriptElement.parentNode.insertBefore(scriptElement, firstScriptElement);
}

Use it like this:

loadScript('url/to/the/first/script.js', function() {
    loadScript('url/to/the/second/script.js', function() {
    // after both scripts are loaded
    });
});

One bugfix which the script includes is the latency bug for IE.

6
  • 1
    Tested: IE7, IE8, IE9, Chrome with 2s latency (sleep)
    – czerasz
    Commented Oct 23, 2012 at 13:15
  • 1
    "One bugfix which the script includes is the latency bug for IE" I can't find any info on this anywhere, can you explain please Commented Dec 1, 2013 at 0:40
  • Without the ieLoadBugFix I got issues while serving the file with a delay. Force Your server to wait 2s before it returns the file to observe it.
    – czerasz
    Commented Dec 1, 2013 at 6:57
  • How often can this happen? What are the chances? I haven't experienced this yet. Commented Dec 1, 2013 at 11:30
  • OR could this be because you are loading async = false? Commented Dec 1, 2013 at 11:31
0

You are loading script from external source. So you need to wait until it loads. You can call your function after id completed.

var headID = document.getElementsByTagName("head")[0]; 
var script = document.createElement('script'); script.type='text/javascript'; 
script.onload=scriptLoaded;
script.src="js/ordini/ImmOrd.js"; script.setAttribute("onload", "crtGridRicProd();");
headID.appendChild(script);

function scriptLoaded(){
// do your work here
}
0
0

When I red your code, I figured out that you try to append an onload event to the script tag.

<html>
 <head>
  <script type="text/javascript" onLoad="crtGridRicPrdo()">
   ...
  </script>
 </head>
 <body>
  ...
 </body>
</html>

This will be the result of your javascript code. Why don't you add it to the body tag? This is the classic way and will defnatly work under IE too. This will also reduce your code:

var bodyID = document.getElementsByTagName("body")[0];
bodyID.setAttribute("onload", "crtGridRicProd();");
5
  • this is good solution but i have more of this:bodyID.setAttribute("onload", "crtGridRicProd();"); becouse i have to load dynamically different script for every tree menu click
    – Marco
    Commented Jul 4, 2011 at 9:12
  • you can add more than one method call. What you have to do is just call methods with different names.
    – Reporter
    Commented Jul 4, 2011 at 9:40
  • yes i have to call different metods from differnt js file at every click
    – Marco
    Commented Jul 4, 2011 at 10:01
  • i have to insert a is file script every click node, so the html show before that i vae clcik, and i receive undefined crtGridRicProd() error
    – Marco
    Commented Jul 4, 2011 at 10:35
  • this has poor IE support
    – Dan
    Commented Nov 7, 2014 at 11:16
0

For proberly dynamic loading a js-script (or css-file) in IE you must carefully check the path to the loaded file! The path should start from '/' or './'.

Be aware, that IE sometimes loses leading slash - as for instance is described here: https://olgastattest.blogspot.com/2017/08/javascript-ie.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.