开发者

JavaScript inline event listeners...do they wait for JS to load?

开发者 https://www.devze.com 2023-02-21 18:51 出处:网络
I normally work with jQuery as it\'s convenient to use the document ready feature so I can wait until the DOM is ready before attaching event listeners to DOM elements.

I normally work with jQuery as it's convenient to use the document ready feature so I can wait until the DOM is ready before attaching event listeners to DOM elements.

I've inherited a project that, at least for a while, is going to be using a lot of inline event calls:

<element onclick="doThis()">

Not pretty, but what I have to work with.

Normally I'd load the JS file at the bottom of the HTML page. However, if I do that in this case, does the event wait until the document is ready (body load) to try an execute, or will that onclick event fire as soon as the element is clicked regardless of whether or not that 开发者_StackOverflow中文版big JS file has loaded yet?

I think the latter happens, meaning that in this situation, I can't be moving my JS file out of the HEAD for now. But wanted to confirm.


An event handling attribute on an HTML element is like a mini script block which is evaluated independently of other script blocks on the page. In the case of onclick="", as soon as the element is read into the DOM, the event handler attribute has been evaluated and will attempt to run if the element is clicked.

You can think of those attributes, by the way, as functions. The code between the double quotes of the attribute definition is the same as the code between the curly braces of a function definition.

onclick="/* IN HERE */"

is the same as

elem.onclick= function(){/* IN HERE */};

The function is defined upon being evaluated by the browser, and executed upon click.

If anything provides for the code in the /* IN HERE */ area and has not been loaded into the DOM by the time the element makes it into the DOM, clicking will cause an error.

As I said, all script blocks and inline handlers are evaluated separately. So your scenario of clicking is the same as follows:

<!-- same as firing the click event -->
<script type="text/javascript">
    doSomething();
</script>
<!-- externally loaded script file--late! -->
<script type="text/javascript" src="/path/to/provides_doSomething.js"></script>


yep. when you click, the onclick event will fire even while your javascript scripts is loading. it will append the function call to the queue and when your script isn't loaded yet, it would result to an error. so maybe you can add bit in your code to check if its loaded:

<element onclick="if (doThis) {doThis();}">


The user won't be able to click the element before the DOM is ready.

0

精彩评论

暂无评论...
验证码 换一张
取 消