1

Here my javascript code:

<script type="text/javascript">
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "//mysite.co/js.js";
document.body.appendChild(js);

alert(x);

</script>

In mysitecom/js.js file is like that

var x = '1233123';
//some code

The problem is the alert doesn't work. In google chrome's console says

Uncaught ReferenceError: x is not defined mypage:31 (anonymous function)

But if i include external js file like that;

<script src="//mysite.co/js.js" type="text/javascript" ></script>

It works.

But i need the first method...

What is the fix?

Thanks.

someday
  • 11
  • 1

1 Answers1

1

When you append script tags to the body, they load as they can, rather than in order. That's why you want to add listeners for when the document is done loading. For example, the classic jquery case -

$.ready(function () {
    alert(x);
});

This should work, as the script tag has been loaded by this time, and x has been defined. Also, since you've added the script tag programatically, the browser is going to continue with the script chunk that alerts x, rather than waiting for the script referenced to load.

Edit - a non-jquery way of doing this is mentioned in Javascript - How to detect if document has loaded (IE 7/Firefox 3)

Per @nrabinowitz - http://jsfiddle.net/7br7q/ should show that .ready will indeed take into account dynamically added scripts.

Community
  • 1
  • 1
Stephen
  • 5,362
  • 1
  • 22
  • 33
  • Will `$.ready` actually wait for a tag that's being appended dynamically? – nrabinowitz Dec 03 '13 at 23:30
  • The key point in this answer is that hard-coded script tags load sequentially, but dynamically appended script tags will load asynchronously, and their contents won't be available immediately. – nrabinowitz Dec 03 '13 at 23:32
  • Thanks for reply. But, how google analytics done this? Also it is a multisite project so i can't use jquery. – someday Dec 03 '13 at 23:32
  • @someday - the code is very, very simple. Take a look at the answer that I linked in my answer. You can do something similar. – Stephen Dec 03 '13 at 23:36
  • @Stephen I need a simple call. Also I want to do it anywhere in my page like google analytics. I see your link. I achieve to alert. But to alert, i have to write readyStateCheckInterval. Is there any simple way to do this? – someday Dec 04 '13 at 21:16