简体   繁体   中英

Moving inline js into external js file causing errors

I was trying to tidy up the inline js scripts for a template I'm modifying and combining them into an external js file when I noticed some errors in the console. They are not doing any harm to the site's functionality but I am wondering what I'm doing wrong and how to fix it.

My external js file is:

<script type="text/javascript" src="web/js/init.js"></script> 

Link 1 throws the following error:

Uncaught TypeError: Object [object Object] has no method 'owlCarousel' 

(I don't use that carousal on that page...)

Link 2 where I do use the carousal throws this error:

Uncaught TypeError: Object [object Object] has no method 'nivoSlider' 

(I don't use the slider on that page)

Link 3 I left the inline scripts (no external js file) in place and no js errors relating to external/internal js.

Thanks!

You are calling nivoslider() and not using its js file that why you are getting error for nivoslider, remove the below lines from your init.js From your puppies page

$(window).load(function() {
   $('#slider').nivoSlider();
});

Same problem with you owlcarousel remove the below code from init.js for your index page

$("#owl-example").owlCarousel({
    autoPlay: 3000, //Set AutoPlay to 3 seconds
    items : 3,
    itemsDesktop : [1199,3],
    itemsDesktopSmall : [979,3]
}); 

If your id slider and owl-example used for nivoslider and owlCarousel only then you can do it by checking length of your elements like,

$(function() {
   if($('#slider') && $('#slider').length){// must be on puppies page only
       $('#slider').nivoSlider();
   }
   if($('#owl-example') && $('#owl-example').length){// must be on index page only
      $("#owl-example").owlCarousel({
         autoPlay: 3000, //Set AutoPlay to 3 seconds
         items : 3,
         itemsDesktop : [1199,3],
         itemsDesktopSmall : [979,3]
      });
   }
});

1) You are targeting an element that does not exist on the page. There is no element with an ID of owl-example , so jquery returns nothing and a method is being called on this null value. ( See here on SO how to test for null first )

2) Same as above but with an element with the ID of slider . It doesn't exist on this page, so a method is being called on null.

Your code looks like

$(function(){
  //Code..
})

These functions are all being called when the DOM loads. See this SO question .

3) You are not getting errors on this page because the jquery selectors you are using are returning elements in the page that match. This doesn't have anything to do with inline/external.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM