【问题标题】:Stopping scripts from running on pages they're not needed停止脚本在不需要的页面上运行
【发布时间】:2017-10-19 14:17:46
【问题描述】:

我有 2 个脚本(JS + CANVAS)并不是每个页面都需要的,但是它们包含在一个全局 JS 文件中,因此会出现一些控制台错误。

我设法解决了类似的问题,方法是在运行脚本之前检查父 div 是否在页面上,方法是这样包装它:if ($('#parent-div').length > 0) {} ...但是我似乎无法让它与另一个一起工作我遇到问题的脚本。

脚本的开头比较短:

$(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
    });
});

我原以为我之前给出的示例可以很好地解决这个问题,但显然不是。可能正在做一些愚蠢的事情/错过了一些明显的事情。

canvas 脚本非常长,但我将其全部包含在内,因为我认为这样最好:

$(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);
    }
});

我假设其中有一些东西我可以使用if 语句定位,但我还没有找到它。谁能给点建议?

【问题讨论】:

    标签: javascript jquery html if-statement canvas


    【解决方案1】:

    我不知道这是否适合你,但我会使用放置在 body 元素上的类来指示脚本是否应该运行。类似:

    <body class="canvas-on">
    

    检查每个脚本开头的类。

    或者您可以尝试使用 RequireJS 之类的东西来加载所需的 js 文件,基于 body 具有上面介绍的类机制,如果不需要,则完全跳过加载文件。

    【讨论】:

    • 谢谢,这似乎是个好主意,但我认为我不能在不同页面的正文标签上添加不同的类。否则那将是理想的!
    • 你可以在你的代码中改变什么?正在使用 cms 什么的?
    • javascript 文件本身。只是想在相关代码中检查父 id/class 在运行之前是否存在。
    • 我上次尝试这个时一定出了问题,但我将视差脚本包装在这个if ($('#metropallax').length &gt; 0) { --CODE-HERE-- } 中,它似乎已经成功了......这有什么不好的吗方法?不,我把if 放在function 中,就像这样$(function(){ --HERE-- }); - 可以吗?
    猜你喜欢
    • 2017-07-19
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    相关资源
    最近更新 更多