Using $.getScript (jquery): code is not executed
Asked Answered
R

2

8

I am working on updating my website, which now uses an AJAX engine. My engine works well, up-to-hand for some reason some pages do not execute javascript, let me explain: when the anchor change I use $.get for data recovery. The pages have this structure:

title
h1
script1.js,script2.js,etc.js
style1.css,style2.css,etc.css
<!--there's the page's content-->

It appears reload the page solves the problem, but i don't understand what is different. In the previous code, the engine runs successfully, reloaded or not:

$.getScript("script1.js");
$.getScript("script2.js");
$.getScript("etc.js");


In addition, a php generated script contains user's current state under an Object form:

$(function(){
    user = new Object();
    user.id = user.logged = <?php echo $user->getId();?>;
    user.nick = "<?php echo $user->getNick();?>";
    user.mail = "<?php echo $user->getMail();?>";

    user.logout = function(){

    };
});

The $.getScript request is successful, but the user object is not changed. The script, however, has yet been modified. And it don't works from console too.

The update is currently online at v2.wawolf.com, you'll find everything you need. Hotlink: Engine's code

Ripping answered 6/1, 2015 at 5:8 Comment(2)
May be a silly question; but are you sure jquery itself got loaded?Bayer
jquery is always loaded because going on / loads main.php who loads jquery and other scripts. On this other scripts is page.js who loads the anchor's url.Ripping
R
6

I just solved my problem: when all document is loaded, $(function(){}) will not work again, so calling a script which uses $(function(){}) will no get run. I removed it from all my secondary-called scripts and now all works perfectly!

Ripping answered 10/1, 2015 at 12:25 Comment(0)
S
1

it might just be a loading order issue.

try encapsulating the JS loading in an onload function

$(window).load(function(){ 
    //get script loads here 
}

or

$(document).ready(function() {
   //get script loads here 
}

Sometimes I use one inside the other for dynamic JS script that needs to be loaded last.

Selfdiscipline answered 6/1, 2015 at 9:9 Comment(1)
I thinked about it, but i always use $(function(){}) (equivalent) on all my scripts, it's a reflex. Pherpaps the problem come from the fact document is load, but not the request's document when updating current page. I'm gonna try to call scripts after updating and Itell you.Ripping

© 2022 - 2024 — McMap. All rights reserved.