May 13, 2012

how to block the page width javascript

Question by yobin

...
<head>
    <script type="text/javascript" src="a.js"></script>
</head>
<body>
    <button id="test">click me</button>
    <script type="text/javascript">
        show();
        document.getElementById('test').onclick=function(){
            show();
        }
    </script>
</body>
</html>

the code above:

I put the a.js in the <head> tag, in a.js there’s a b.js created by

document.getElementsByTagName('head')[0].appendChild(document.createElement('script'));  function show(){...} 

in b.js;

now I want to invoke show() which in the b.js,but it goes error,because b.js hasn’t loaded;

I want to add some codes to block the page loading.

while(){} ?


actually,I learned b.js should be loaded when function show is invoked;

but what about click event?in addition,I must put the show() in the page.

now,I put another js(base.js) into head tag,the above code will be like this:

...
<head>
<script type="text/javascript" src="base.js"></script>
<script type="text/javascript" src="a.js"></script>
</head>
<body>
    <button id="test"></button>
    <script type="text/javascript">
        //invoke button click event from base.js and b.js
    </script>
</body>
...

for example,there are two click events bind to base.js and b.js(loaded ansync by a.js),when users click the button in the page,the event binded in base.js will be invoked immediately,but then…error…

I must put the invoker in the body tag.

Answer by Starx

Instead of blocking the page load, why dont you run the code on the onload event of the window?

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

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!