2017-10-19 21 views
0

J'ai 2 scripts (JS + CANVAS) qui ne sont pas nécessaires sur chaque page, mais ils sont inclus dans un fichier JS global et, pour cette raison, quelques les erreurs de la console apparaissent. J'ai réussi à résoudre un problème similaire en vérifiant que la div parente était sur la page avant d'exécuter le script en l'entourant de quelque chose comme ceci: if ($('#parent-div').length > 0) {} ... mais je n'arrive pas à le faire fonctionner avec l'autre script J'ai des problèmes avec.Arrêter l'exécution des scripts sur les pages dont ils n'ont pas besoin

Le premier bit de script est relativement courte:

$(function(){ 
    var scene = document.getElementById('metropallax'); 
    var parallaxInstance = new Parallax(scene, { 
     relativeInput: true, 
     calibrateX: false, 
     calibrateY: true, 
     invertX: false, 
     invertY: true, 
     limitX: false, 
     //limitY: 10, 
     limitY: 0, 
     scalarX: 2, 
     scalarY: 8, 
     frictionX: 0.2, 
     frictionY: 0.8, 
     originX: 0.0, 
     originY: 1.0 
    }); 
}); 

j'aurais pensé l'exemple que je donnais, auparavant, travailler très bien avec cela, mais apparemment pas. Probablement faire quelque chose de stupide/manquer quelque chose d'évident.

Le script canvas ridiculement long, mais je rajouterais tout comme je pense que ça serait le mieux:

$(function(){ 

    // Create an array to store our particles 
    var particles = []; 

    // The amount of particles to render 
    var particleCount = 8; 
    // Orig 30 

    // The maximum velocity in each direction 
    var maxVelocity = 4; 

    // The target frames per second (how often do we want to update/redraw the scene) 
    var targetFPS = 24; 
    // Orig 33 

    // Set the dimensions of the canvas as variables so they can be used. 
    var canvasWidth = 400; 
    var canvasHeight = 400; 

    // Create an image object (only need one instance) 
    var imageObj = new Image(); 

    // Once the image has been downloaded then set the image on all of the particles 
    imageObj.onload = function() { 
     particles.forEach(function(particle) { 
       particle.setImage(imageObj); 
     }); 
    }; 

    // Once the callback is arranged then set the source of the image 
    imageObj.src = "http://www.blog.jonnycornwell.com/wp-content/uploads/2012/07/Smoke10.png"; 

    // A function to create a particle object. 
    function Particle(context) { 

     // Set the initial x and y positions 
     this.x = 0; 
     this.y = 0; 

     // Set the initial velocity 
     this.xVelocity = 0; 
     this.yVelocity = 0; 

     // Set the radius 
     this.radius = 5; 

     // Store the context which will be used to draw the particle 
     this.context = context; 

     // The function to draw the particle on the canvas. 
     this.draw = function() { 

      // If an image is set draw it 
      if(this.image){ 
       this.context.drawImage(this.image, this.x-128, this.y-128);   
       // If the image is being rendered do not draw the circle so break out of the draw function     
       return; 
      } 
      // Draw the circle as before, with the addition of using the position and the radius from this object. 
      this.context.beginPath(); 
      this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false); 
      this.context.fillStyle = "rgba(0, 255, 255, 1)"; 
      this.context.fill(); 
      this.context.closePath(); 
     }; 

     // Update the particle. 
     this.update = function() { 
      // Update the position of the particle with the addition of the velocity. 
      this.x += this.xVelocity; 
      this.y += this.yVelocity; 

      // Check if has crossed the right edge 
      if (this.x >= canvasWidth) { 
       this.xVelocity = -this.xVelocity; 
       this.x = canvasWidth; 
      } 
      // Check if has crossed the left edge 
      else if (this.x <= 0) { 
       this.xVelocity = -this.xVelocity; 
       this.x = 0; 
      } 

      // Check if has crossed the bottom edge 
      if (this.y >= canvasHeight) { 
       this.yVelocity = -this.yVelocity; 
       this.y = canvasHeight; 
      } 

      // Check if has crossed the top edge 
      else if (this.y <= 0) { 
       this.yVelocity = -this.yVelocity; 
       this.y = 0; 
      } 
     }; 

     // A function to set the position of the particle. 
     this.setPosition = function(x, y) { 
      this.x = x; 
      this.y = y; 
     }; 

     // Function to set the velocity. 
     this.setVelocity = function(x, y) { 
      this.xVelocity = x; 
      this.yVelocity = y; 
     }; 

     this.setImage = function(image){ 
      this.image = image; 
     } 
    } 

    // A function to generate a random number between 2 values 
    function generateRandom(min, max){ 
     return Math.random() * (max - min) + min; 
    } 

    // The canvas context if it is defined. 
    var context; 

    // Initialise the scene and set the context if possible 
    function init() { 
     var canvas = document.getElementById('smoke'); 
     if (canvas.getContext) { 

      // Set the context variable so it can be re-used 
      context = canvas.getContext('2d'); 

      // Create the particles and set their initial positions and velocities 
      for(var i=0; i < particleCount; ++i){ 
       var particle = new Particle(context); 

       // Set the position to be inside the canvas bounds 
       particle.setPosition(generateRandom(0, canvasWidth), generateRandom(0, canvasHeight)); 

       // Set the initial velocity to be either random and either negative or positive 
       particle.setVelocity(generateRandom(-maxVelocity, maxVelocity), generateRandom(-maxVelocity, maxVelocity)); 
       particles.push(particle);    
      } 
     } 
     else { 
      alert("Please use a modern browser"); 
     } 
    } 

    // The function to draw the scene 
    function draw() { 
     // Clear the drawing surface and fill it with a black background 
     context.fillStyle = "rgba(0, 0, 0, 0.5)"; 
     context.fillRect(0, 0, 400, 400); 

     // Go through all of the particles and draw them. 
     particles.forEach(function(particle) { 
      particle.draw(); 
     }); 
    } 

    // Update the scene 
    function update() { 
     particles.forEach(function(particle) { 
      particle.update(); 
     }); 
    } 

    // Initialize the scene 
    init(); 

    // If the context is set then we can draw the scene (if not then the browser does not support canvas) 
    if (context) { 
     setInterval(function() { 
      // Update the scene befoe drawing 
      update(); 

      // Draw the scene 
      draw(); 
     }, 1000/targetFPS); 
    } 
}); 

Je suppose qu'il ya quelque chose là-dedans, je peux cibler l'aide d'une déclaration if mais je n » Je l'ai encore trouvé. Quelqu'un peut-il conseiller?

Répondre

1

Je ne sais pas si cela fonctionne pour vous, mais j'utiliserais des classes placées sur l'élément body pour indiquer si le script devrait fonctionner ou non. quelque chose comme:

<body class="canvas-on"> 

Vérifiez la classe au début de chaque script.

Ou vous pourriez essayer d'utiliser quelque chose comme RequireJS pour charger les fichiers js nécessaires en fonction du corps a le mécanisme de classe présenté ci-dessus et de ne pas charger les fichiers du tout si ce n'est pas nécessaire.

+0

Merci, cela semble être une bonne idée mais je ne pense pas que je puisse ajouter des classes différentes sur les balises de corps de différentes pages. Sinon, ce serait idéal! – user1406440

+0

que pouvez-vous changer dans votre code? utilisez un cms ou quelque chose? –

+0

Le fichier javascript lui-même. Je veux juste vérifier, dans le bit de code correspondant, que l'ID/classe parent est présent avant de l'exécuter. – user1406440