Javascript includes not loading for later in the page

前端 未结 7 2510
我寻月下人不归
我寻月下人不归 2021-02-20 08:42

We have a Rails application where we are including our application dependencies in the html head within application.js:

//= require jquery
//= requi         


        
7条回答
  •  心在旅途
    2021-02-20 09:04

    The basis of your problem probably lies in your assumption:

    everything should be loaded synchronously

    Everything is most decidedly not loaded synchronously. The HTTP 1.1 protocol supports piplining and due to chunked transfer encoding, your referenced objects may or may not complete loading before your main webpage has finished loading.

    All of this happens asynchronously and you can't guarantee the order in which they are loaded. This is why browsers make multiple parallel connections to your web server when loading a single webpage. Because javascript and jQuery are event driven, they are by nature asynchronous which can become confusing if you don't understand that behavior well.

    Compounding your problem is the fact that document onload JavaScript event (remember, jQuery just extends JavaScript) "is called when the DOM is ready which can be prior to images and other external content is loaded." And yes, this external content can include your link to the jquery.js script. If that loads after the DOM, then you will see the error "$ is not defined". Because the linked script has not yet loaded, the jquery selector is undefined. Likewise, with your other linked libraries.

    Try using $(window).load() instead. This should work when all the referenced objects and the DOM has loaded.

提交回复
热议问题