jquery source's position in html file is important or not

后端 未结 5 943
再見小時候
再見小時候 2021-01-21 16:38

This is an example of click button to pop up an alert.



        
5条回答
  •  伪装坚强ぢ
    2021-01-21 16:53

    This answer is for those who are in the mystery why sometimes the code works and sometimes it does not when placing the library source at the bottom of the page.

    After being in this mystery myself for quite a while, I featured it. There are 2 separate and distinct concerns in this matter, one is about executing the code and one is about loading the code.

    The placement of jquery source does not matter as long as you are not executing any code when loading the page. Yes, you read that right and it absolutely correct.

    Please allow me to elaborate with an example;

    
    
    
    

    The code above will be executed when the page is loaded. As you can see $("#emailInput"), having the jquery selector, is executed before the jquery library has been loaded and executed (this is where jquery will define $ and all the things it does). This is what causes the error Uncaught ReferenceError: $ is not defined to be thrown.

    However, if the code is not executed when the page is loaded, we will not have any errors, this is also best explained with an example.

    
        
            
        
        
            
    
            

    The code above is complete and correct, so you can try it to see it for yourself and it works absolutely fine. This is because the function writeMessage() has not been executed when the page was loaded. The function is executed only when the button is pressed; which is after the page has been loaded (by that time the jquery library has already been loaded and executed).

    I have seen in the comments, in this link the code is working when the library is loaded after. Remove the jquery src found at the bottom, run it again and the jquery still works! My best guess would be, the code is using the library which is available on jsfiddle's website.

    I hope this clarifies the mystery we all have been living in.

提交回复
热议问题