简体   繁体   中英

Javascript - Function VS No Function…how does this work?

If I place the following script above the element that the script is searching for, I receive an error:

<script type="text/javascript">
document.getElementById('my_iframe').src = "my_file.php";
</script>

And of course, to get it working again I need to place it below the element.

Yet if I turn the same thing into a function and place it above the element that the script is searching for, it works perfectly:

function loadnew(){
    document.getElementById('my_iframe').src = "my_file.php";
}

The question is, why does it work if I use a function? I always thought that in order for a script to find something it needed to be placed below the element it's searching for?

Thanks!

Where it's placed does not matter, the only thing that matters is when it is executed.

If it's executed before there is a element with the id my_iframe it will fail, if there is one it will succeed.

So if you just do a inline script tag and then place your one liner in there it will be executed immediately and if the script tag happens to be before the tag with the id my_iframe nothing is found - getElementById returns null which isn't a normal object and therefore can't have a property src so your code fails.

If you define a function and execute it after a element with the id my_iframe exists it will return a element object and your code runs fine (of curse assuming that element object allows the src property to be set).

You need to execute this code when the DOM is ready.

window.onload=function(){
  loadnew()
}

Javascript code is executed as encountered by the browser's parser 1 . Which means that if you query an element below your <SCRIPT> tag, it won't find it because the element below it has not yet been executed created.

However, since you place your code inside a function, what is executed is the creation of the function, not the code inside it. Therefore it will work for your provided case (since you're not calling that function).

If you need more clarifications, I can provide more details and examples.


[1] Note that some browsers may execute Javascript in a separate thread than the HTML renderer, however it's still executed as encountered.

It sounds like you are putting the script in the body. If you place it in the body, you are giving all of your power away to the browser vendor.

Each browser will handle execution of script in the body slightly different. Most will run it in the order that it's parsed. The exact time that this happens will be different, causing different behavior in other browsers.

Explanation :

In other words, if your globally-scoped code, not wrapped in a function is placed above a DOM element that has not yet rendered, then that code will cause an error since the object in question is undefined.

When the code is below the element, the browser generally has time to render the DOM element before the code runs.

It's just plain messy to see JavaScript strung all over an HTML document. It creates a maintenance nightmare. Just ask this poster who is spending his entire day unraveling tangled JavaScript and HTML to find a nasty bug in the code: Debugging HTML & JavaScript with Firebug

Suppose you make an adjustment to the HTML and move elements around on the page. Imagine all of the JavaScript you'd need to shuffle around.

Solution:

To prevent this from becoming an issue, put your script where it belongs, in an external JavaScript file, linked in the head section, as a script tag. The script won't run until the DOM is completely loaded, preventing errors related to elements not yet being in scope, and eliminating the details of worrying about the order in which the files are loaded.

In your first example, the code is executed before the DOM tree is build. 'my_iframe' doesn't exist yet. If you place it below the element, the DOM tree is build and your element exists. By creating a function (and calling it later), you postpone execution of the code until the DOM tree has been build.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM