Javascript does not work from a bootstrap template in rails

前端 未结 3 878
心在旅途
心在旅途 2021-01-16 04:47

I have created a new rails app and installed all the necessary gems. Added all the files. Updated the application.js file. Everything works but for some reason all the javas

相关标签:
3条回答
  • 2021-01-16 05:16

    I have finally managed to make it work! First of all I started from new and I created a new rails app because I was in desperate mode and installed to many Gems and changed the code that at the end the code was a mess.

    This time I took a different approach and I did not use any additional gems and I have installed all the necessary plugins manually meaning just copy and paste all the files in the correct directories and linking them together. I had to delete the coffeescript file inside the javascript directory becuase the file caused some issues. As you can see I also had to put a trigger manually inside the body tag otherwise the ScrollSpy function would not work (data-spy="scroll" data-target=".navbar-fixed-top"). For some reason Javascript still did not work but I have read that Javascript/jQuery can cause some issues if its not loaded properly meaning in the correct oder. So I deleted //= require_tree . in the javascript file. And put each javascript in the correct order. I could figure out the correct oder by looking at the source code of the working template. But it still did not work! I then put the "<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>" at the very end of the tag so the javascript would load last. ... And finally it worked! My next step would be to delete the turbolinks line in the application.js file and I would change:

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %> 
    

    into

    <%= stylesheet_link_tag    'application', media: 'all' %>
    

    Because I have read that turbolinks can cause some issues with the asset pipeline with javascript especially.

    application.html.erb

    <!DOCTYPE html>
    <html lang="en">
      <head>
    
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">
    
        <title>Creativetemplate</title>
        <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
        <%= csrf_meta_tags %>
    
      </head>
    
        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
            <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
            <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
    
      <body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
    
      <%= render 'layouts/header' %>
      <%= yield %>
      <%= render 'layouts/footer' %>
      <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
      </body>
    </html>
    

    application.js

    //= require jquery
    //= require jquery_ujs
    //= require turbolinks
    //= require bootstrap
    //= require jquery.easing
    //= require scrollreveal
    //= require jquery.magnific-popup
    //= require welcomes
    

    welcomes.js

    (function($) {
        "use strict"; // Start of use strict
        // debugger
        // jQuery for page scrolling feature - requires jQuery Easing plugin
        $('a.page-scroll').bind('click', function(event) {
            var $anchor = $(this);
            $('html, body').stop().animate({
                scrollTop: ($($anchor.attr('href')).offset().top - 50)
            }, 1250, 'easeInOutExpo');
            event.preventDefault();
        });
    
        // Highlight the top nav as scrolling occurs
        $('body').scrollspy({
            target: '.navbar-fixed-top',
            offset: 51
        });
    
        // Closes the Responsive Menu on Menu Item Click
        $('.navbar-collapse ul li a').click(function() {
            $('.navbar-toggle:visible').click();
        });
    
        // Offset for Main Navigation
        $('#mainNav').affix({
            offset: {
                top: 100
            }
        })
    
        // Initialize and Configure Scroll Reveal Animation
        window.sr = ScrollReveal();
        sr.reveal('.sr-icons', {
            duration: 600,
            scale: 0.3,
            distance: '0px'
        }, 200);
        sr.reveal('.sr-button', {
            duration: 1000,
            delay: 200
        });
        sr.reveal('.sr-contact', {
            duration: 600,
            scale: 0.3,
            distance: '0px'
        }, 300);
    
        // Initialize and Configure Magnific Popup Lightbox Plugin
        $('.popup-gallery').magnificPopup({
            delegate: 'a',
            type: 'image',
            tLoading: 'Loading image #%curr%...',
            mainClass: 'mfp-img-mobile',
            gallery: {
                enabled: true,
                navigateByImgClick: true,
                preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
            },
            image: {
                tError: '<a href="%url%">The image #%curr%</a> could not be loaded.'
            }
        });
    
    })(jQuery); // End of use strict
    

    application.css.scss

    /*
    *= require magnific-popup
    *= require welcomes
    */
    
    @import "bootstrap";
    @import "font-awesome";
    
    html,
    body {
      height: 100%;
      width: 100%;
    }
    
    ...
    ...
    ...
    

    If someone has similar issues with Javascript and the Asset Pipeline this is how I would try to solve it:

    1) Make sure that all the files are in the correct directory

    2) Check if all the files are correctly linked together inside the application.css.scss, application.js and application.html.erb

    3) Delete the "//= require_tree ." line in application.js because it loads the javascript with no specific order and it could create some issues. Type every line manually in the correct order of the theme. You can check the correct oder by looking at the source code of the template in the browser.

    4) Check if the correct version number of the plugins are installed by comparing the source code when you run your localserver and check the website with the template website.

    5) If you don't need the coffeescript file in the javascript directory then delete it.

    6) Move the "javascript_include_tag" from inside the head tag right above the closing body tag. So the javascript can get loaded last.

    7) Get rid of turbolinks in application.js and application.html.erb.

    8) If it still does not work check the Developer Tools(Console) in Chrome of the website and you can use also a debugger in the javascript file to see if there are any errors.

    Hopefully it helps someone.

    0 讨论(0)
  • 2021-01-16 05:29

    The tricky part is around the welcomes.js and the turbolinks. Convert your welcomes.js to coffee (with js2coffee for example) and then copy it in a file like home.coffee on your app/assets/javascripts. The key is at the first line to add $(document).on "turbolinks:load", ->

    $(document).on "turbolinks:load", ->
      (($) ->
        'use strict'
        # Start of use strict
        # jQuery for page scrolling feature - requires jQuery Easing plugin
        $('a.page-scroll').bind 'click', (event) ->
          $anchor = $(this)
          $('html, body').stop().animate { scrollTop: $($anchor.attr('href')).offset().top - 50 }, 1250, 'easeInOutExpo'
          event.preventDefault()
          return
        # Highlight the top nav as scrolling occurs
        $('body').scrollspy
          target: '.navbar-fixed-top'
          offset: 51
        # Closes the Responsive Menu on Menu Item Click
        $('.navbar-collapse ul li a').click ->
          $('.navbar-toggle:visible').click()
          return
        # Offset for Main Navigation
        $('#mainNav').affix offset: top: 100
        # Initialize and Configure Scroll Reveal Animation
        window.sr = ScrollReveal()
        sr.reveal '.sr-icons', {
          duration: 600
          scale: 0.3
          distance: '0px'
        }, 200
        sr.reveal '.sr-button',
          duration: 1000
          delay: 200
        sr.reveal '.sr-contact', {
          duration: 600
          scale: 0.3
          distance: '0px'
        }, 300
        # Initialize and Configure Magnific Popup Lightbox Plugin
        $('.popup-gallery').magnificPopup
          delegate: 'a'
          type: 'image'
          tLoading: 'Loading image #%curr%...'
          mainClass: 'mfp-img-mobile'
          gallery:
            enabled: true
            navigateByImgClick: true
            preload: [
              0
              1
            ]
          image: tError: '<a href="%url%">The image #%curr%</a> could not be loaded.'
        return
      ) jQuery
    

    and everything works fine! Don't change anything else. Setup your js manifest with the correct js files for your template and you're ready.

    0 讨论(0)
  • 2021-01-16 05:36

    I am editing my answer, because I still had problems with the Asset Pipeline.

    I add the following resources that may help in finding a solution and I will post the solution to the problem once I solved it.

    https://launchschool.com/blog/rails-asset-pipeline-best-practices

    https://railsapps.github.io/rails-javascript-include-external.html

    https://reinteractive.com/posts/116-12-tips-for-the-rails-asset-pipeline

    I read all the guides that can be found by searching rails asset pipeline, but I will not link them all

    My advice is to check the fingerprint of the application.css and application.js both with the Chrome Developer Tools (by going in any screen element, opening the developer toolbox with f12 and checking any style of any div or any js file). You will need to check which fingerprint version of the file is used, then open that version with the text editor and check what is loaded in the fingerprint version of the file.

    If your file (for ex. user.js) is loaded at the bottom of the manifest, you should easily find it at the bottom of your fingerprinted application.js.

    If you want to update this file you can run

    rake assets:precompile

    This will precompile assets only in development, for production you need to specify the environment. It will change that fingerprinted file application.css and application.js with the editing you have done.

    You can also check the file at the following address localhost:3000/assets/yourjsfile.js or check the fingerprint version by following localhost:3000/assets/application-yourfingerprint.js

    As you can see, many files are included in that public/assets folder, you can delete them with rake assets:clean or -rf public/assets and then run rake assets:precompile, it will precompile again assets.

    If nothing is included, then your application.js is not being loaded. You may try the following as I read on different posts:

    1. Include the file in the config/initializers/assets.rb with the following line of code:

      Rails.application.config.assets.precompile += %w( user.js )
      
    2. Start the rails c and run Rails.application.config.assets.paths This command will show in red the paths that are automatically included, for example those inside App, Lib and Vendor, in green those that you included by adding inside config/application.rb the follwing code to add new path

      config.assets.paths << Rails.root.join("vendor","assets", "fonts")
      

    Another error i made in the past was not using the correct sprockets syntax, you can check it at the following link ( i was using require_user instead of require user):

    https://github.com/rails/sprockets#sprockets-directives

    My problem was that I had under App/assets/javascript two files named user (user.coffee and user.js). The first to be loaded was user.coffee which was empty. I found the solution thanks to the answer of trickydiddy

    0 讨论(0)
提交回复
热议问题