2

I am sharing a script tag with client to deploy my web application on client's website.

Basically by this way, he can embed my app wherever he want on his site.

The script which I give him just calls one action method in my MVC application and receives a javaScript as a response.

As a fist step, this returned JavaScript inserts all js and css references (required by my application) in the client's head tag

function createScriptElement(src) {
    var tmp = document.createElement("script");
    tmp.src = src;

    var head = document.getElementsByTagName("head")[0];
    head.appendChild(tmp);
};

and then in second step, it writes the html content inside one dynamic div.

document.write(format("<div id='mycontainer'>{0}</div>{1}", AppHtml,initcalls ));

The "initcalls" contains the initial function in my app's javascript which I expect to execute immediately. So I put it in Script tag as below.

contents of initcalls are:

<script type=\"text/javascript\">     function icInitApp() { ..... }; </script>

The problem is: there are some dependencies in my application on the js references. The HTML is getting loaded before the head tag in client's page recognizes and loads the js references.

Is there any way to hold my (thus dynamically rendered) application's init function until all js references are fully loaded by head tag?

I tried giving setTimeout() with 5 seconds but it will not be proper solution accepted by client.

Anil Soman
  • 2,443
  • 7
  • 40
  • 64

2 Answers2

1

A similar kind of situation is discussed in the link below

How to detect if javascript files are loaded?

You can also try to use the $(window).load() event since this will be fired when the page is fully loaded.

$(window).load(function(){
  //your code here
});

PS: Be aware that you will need to load the jQuery in your page to make the above code work.

Community
  • 1
  • 1
clklachu
  • 951
  • 1
  • 7
  • 19
  • it's calling the code inside load, however it did not resolve the problem. My application is still not able to recognize the js plugin – Anil Soman Dec 14 '12 at 06:16
  • I tried frameworks like LabJs, yepnope.js but it is giving error like "Incorrect Token <" in the js file of framework itself. Any idea on how to get rid of this error? – Anil Soman Dec 20 '12 at 08:54
0

You can try with jQuery:

$(document).ready(function()){
     // Your code goes here
};
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
felipekm
  • 2,820
  • 5
  • 32
  • 42