Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load page javascript after async loading of my manifest file

I am trying to convert my app to asynchronous javascript loading with:

<%= javascript_include_tag "application", async: true %>

The problem is that any page-specific scripts are being run before Jquery is loaded asynchronously. How can I defer those until the application.js manifest file has been loaded.

I tried wrapping my page js in $(window).load(function(){}); but this did not help. I still see the following error:

Uncaught ReferenceError: $ is not defined

Update:

This seems to be working for me, but I'd like someone to confirm that it is the correct approach:

<%= javascript_include_tag "application", async: true, onload: 'pageScripts()' %>

Then the page script like:

<script>
  function pageScripts() {
    // do something
  }
</script>
like image 555
Abram Avatar asked Mar 07 '16 15:03

Abram


People also ask

Is it possible to display page with defer or async completely?

Yes, you can use both attributes but you need to use defer or async, not both. For more see the comparison and use one based on your need. defer attribute: First it will download the script file and then wait of html parsing. After the end of html parsing, script will execute.

What is asynchronous loading Javascript?

Synchronously, where scripts are loaded sequentially, one after another, starting with the <head> tag. Asynchronously, where some scripts can be loaded simultaneously.

How can you ensure the loading of a third party js script doesn't affect the overall loading of a page?

If a third-party script is slowing down your page load, you have several options to improve performance: Load the script using the async or defer attribute to avoid blocking document parsing. Consider self-hosting the script if the third-party server is slow.

How can you make a script run asynchronous?

The async attribute is a boolean attribute. When present, it specifies that the script will be executed asynchronously as soon as it is available. Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).


1 Answers

Your approach is correct however I would suggest to limit your Async only for production since in development Sprockets hasn't concatinated all of the files yet.

<%= javascript_include_tag "application", async: Rails.env.production?, onload: 'pageScripts()' %>
like image 137
svelandiag Avatar answered Sep 27 '22 20:09

svelandiag