Chrome developer tools: save javascript state - javascript

Is it possible to save the current state of a page and it's JavaScript variables in Chrome devtools, in order to later reload that same state?
As some background: I'm working on a project that has a question and answer system. This mechanism is handled by JavaScript and my workflow is awful at the moment because I'm coding question number ten and need to answer the first nine questions each time I need to test my code.
I would like to answer questions 1-9, save the state of the variables on the page, make changes to question 10 code and test after first reloading the state until question 9.

It's difficult to make this work exactly as you describe, since the concept of the variables on the page isn't easy to work with. What would happen if you add a remove a variable name in the code?
There are a few things you could try.
1. Remove the first 9 questions from the quiz
Are they necessary for testing?
2. Find out what variables are set and then back them up
For example, if the window.questionIndex and window.answersGiven properties describe the state of the page you could back them up like this:
function backup(){
localStorage.setItem("questionIndex", JSON.stringify(window.questionIndex));
localStorage.setItem("answersGiven", JSON.stringify(window.answersGiven))
}
function restore(){
window.questionIndex = JSON.parse(localStorage.getItem("questionIndex"));
window.answersGiven = JSON.parse(localStorage.getItem("answersGiven");
}
3. Automate the process of clicking through the quiz
Would a script like this do the trick?
var interval = setInterval(function(){
$("#answer1").click()
}, 100)
setTimeout(function(){
clearInterval(interval);
}, 100 * 9)
4. Develop the last question independently before integrating it
Create an empty page and load only the module for question #10 on it. Once the coe works as expected integrate it into the full quiz.

Related

WooCommerce - Trying to add a custom field text under the product name [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I had been trying to set custom text under the product name in WooCommerce for one of the clients.
There's an Attribute that I created for each product, whose class name is "woocommerce-product-attributes-item woocommerce-product-attributes-item--attribute_underprice".
I'd like to take the value that I set in there and show it on the Product Category page (also known as Product Archive page). Additionally, it'd be great if this could ONLY work for a specific category (URL slug is /product-category/wigs).
I have pretty much never coded in JavaScript before, but from what I understand... it could look something like this?
Needless to say, when I add this code to functions.php, the whole website crashes (I must be missing a lot of things).
I appreciate any and all help!
function UnderPrice() {
var id = document.getElementsByClassName("woocommerce-product-attributes-item woocommerce-product-attributes-item--attribute_underprice");
if (id.length > 0) {
alert (id[0].value);
}
}
remove_action( 'woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title', 10 );
function customize_shop_page_product_title() {
$custom_text = 'My Custom Text';
echo '<h3 class="woocommerce-loop-product__title">' .UnderPrice .$custom_text.'</h3>';
}
add_action('woocommerce_shop_loop_item_title','customize_shop_page_product_title');
I believe you are mixing JS and PHP in the same file. The code crashes because the PHP engine sees a malformed function (because it is JS) and then later you try to concatenate it into a string.
If you want to have the javascript rendered as part of your frontend template, you should put the whole function in a string variable (know though, that this is a bad practice, because it is hard to debug), or import it somehow.
Also it seems that you try to place the javascript function amid a <h3> tag, which would never work in the frontend. The browser will only be able to access any javascript placed between tags, or imported from a .js file by a <script> tag.
The javascript function underPrice seems well-formed, syntactically. (tip: It is customary to use camelCase for functions rather than PascalCase.) Not sure what the function is supposed to do, but this would cause an popup window with some value and an ok button, if it finds the element with the two classes.
I hope this helps you forward somewhat. Since you mention little experience with JS, I would suggest to lookup some tutorials with it, there are many wonderful ones online for free, and it is well worth the time.

Navigate through pages in a paginator using React

First I want to say this is my first question, sorry if it doesn't meet the standards of a quality one (whether it's too messy / badly organized or explained), I'm listening to all kinds of feedback. Also sorry if my english is not perfect, I'll try to be as understandable as possible.
So here is my problem : I'm implementing a React paginator, compatible with server-side content-range pagination. I want to navigate through pages, when there are too much of them.
A basic example without styling available here (EDIT : working, see answer) : https://codesandbox.io/s/w03lkpmy48
(I'm a React rookie, so the quality of my code is probably questionable.)
I created a function calculateNumberOfPages(itemsCount) (l.42) where itemsCount can be a huge number, e.g 7683, to return an int used to create the <li>s.
In the render, I call this function (l.48) to get the number, then I loop on it x times and push <li>s in an array (l.53 to 65).
However, when the itemsCount is huge, that can result in something like this : https://i.imgur.com/zea4QaD.png
which is why I put an ellipsis if the number of pages is above 10 :
https://i.imgur.com/7FstTlO.png
Now, the problem is that I want to navigate through pages, to get next pages (4 by 4). If I click on the 10th page, i should have 10 11 12 13 14 ... 16 (for example), and same when I click on the 10th page, in order to have previous pages.
But I'm logically stuck, and I quite need your help. Some comments in the code might point out what I want to do, but they might be as messy as my logic.
If you have other questions, I'm all ears. Thanks for reading my question !
Okay so I had help from a friend in order to do this.
What was essentially missing in my code was a way to conserve the state of the current page, to compare it. So I added a currentPage property in the state.
Then I added some Javascript (with if/else, needs to be optimized and cleansed) to compare values of the <li>s and the current page.
And I change the values displayed in the render.
You can see all of it in the codesandbox in the question !

Pragmatically Determine EXT JS 6 - Required or Uses subfile

EXTJS 6, Requires or Uses - Determine programatically
At work we are using EXT JS 6, I've been tasked with 'speeding it up'. I've already done several things and have achieved at least a 30% speed increase. However when loading a page/module/section (whatever you want to call it), Every single component underneath the first is loaded async.
This is causing a measurable delay of about 20 seconds on a page load.
I believe this is because when we migrated from EXT JS 4, we kept everything in our class definitions as a requires.
requires: [
'app.view.setup.thing.TabController',
'app.view.setup.thing.Panel',
'app.store.setup.combo.thingGroupIcons'
],
I've look at a lot of documentation and have come to the conclusion that we should be using 'uses' to define sections of the program that can load separately to the 'on-screen-first' stuff.
So for instance, the above would become something like:
requires: [
'app.view.setup.thing.Panel',
],
uses: [
'app.view.setup.thing.TabController',
'app.store.setup.combo.thingGroupIcons'
],
The program probably has a good 500 pages/sections to it. Probably has 3000~ files. So my question is (really two fold).
Question 1: How can I pragmatically determine if something in my 'requires' could/should be loaded using 'uses'
and
Question 2: Am I on the right track at all?
There's a very hostile community around EXT JS, so I'm asking this question on Stack where I hope people will be more helpful. I have spent seven hours so far today reading, and the below are some of the links that I think are actually helpful.
https://www.sencha.com/forum/archive/index.php/t-133191.html?s=8b90c637dd96fed53597cd029544d955
http://docs.sencha.com/extjs/6.0.0/classic/Ext.Class.html#cfg-requires
To determine which ones you can load via uses, you can only move everything from the "required" sections into the "uses" section, and check what's broken.
But with uses, you can only improve the loading time of the uncompiled version, not of the cmd compiled version, where all dependencies are in a single javascript file, and which should be the only version facing the customer.
Of course, you can always do the same as my boss did, and get some Highly Paid Consultants™ (from Sencha or a Sencha-approved outlet near you) to review your application. Their first result was exactly what I already told him: that there is no possibility to significantly improve the loading speed of our Cmd-compiled version further. They told us that we had only one option left - I should add an animated splash screen, which would cut down the loading time in half. It doesn't if you use a stop watch, of course, but the user does not have a stop watch when he starts the application...

Using GreaseMonkey to change Javascript variable

I've got a question regarding a website that I use quite frequently. The website is essentially a browser-based air traffic control simulator. The page uses a php script to load the JavaScript directly into the browser when the game is initiated.
So, here is my question. In the JavaScript code, there is a function that is called when a new aircraft is generated on the screen.
function fnNewOne() { /* New aircraft generation code }
In the code, there is a command that sets the altitude of the plane to a certain height and then stores this value in a global variable. I wanted to know if it would be possible to alter this variable externally using a GreaseMonkey script in order to generate a different altitude. For example, I want flights to only enter the screen at a minimum altitude of 13,000 ft. How could I use GreaseMonkey to target the altitude variable? And when would be most appropriate to change the altitude that has initially been set by the game? What kind of event listener could I use?
If anyone could assist me in this, I would be very grateful.
The answer is that you just write your code in a GreaseMonkey script... There's nothing special about it.
It will be executed after the page loads, but there is a chance that your code will execute before the game initializes, so maybe you should set an interval to 100ms and watch for window.hasOwnProperty('altitude') to make sure the game is initialized (or whatever variable you want to fiddle with) and when that property is found, call whatever code you need and then clear your interval.
This is the best answer I have for you, given how poor your question is. Maybe if you gave us a few more details we'd be able to provide you with some better answers. What exactly are you trying to do? (what variable do you want to change, how and when?) What did you try? Do you have a JS question or a GM question? Have you checked out the GM documentation for examples? (there are very few, very succinct examples from which you can learn 95% of GM in a couple of hours)

How to trace slow JS or JQuery code

I created a web page for viewing images. This page has some other code that gets included that I did not write. The page loads 40 small images upon load. Then the user will scroll down and additional pages of 40 images can be loaded via ajax. Once I get to 15-20 pages, I notice the page begins to slow significantly. I check app counters and it can go up to 100% cpu and memory can go over 3GB. Then I will inevitably get the modal that JQuery is taking too long to execute, asking me if I want to stop executing the script. Now I realize that a page with up to 800 images is a big load, but the issue with JQuery suggests to me that some code may also be iterating over this larger and larger group of dom objects. It almost appears to get exponentially slower as I pass 15 pages or so. Once I get to 20 pages it becomes almost unusable.
First of all, is it even possible to run a page efficiently, even with minimal JS, when you have this many images? Secondly, is there a recommended way to "trace" JS and see what kinds of functions are getting executed to help determine what is the most likely culprit? This is most important to me - is there a good way to do in Firebug?
Thanks :)
EDIT - I found my answer. I had some older code which was being used to replace images that failed to load with a generic image. This code was using Jquery's .each operator and thus was iterating over the entire page and each new ajax addition every time the page loaded. I am going to set a class for the images that need to be checked in CSS so that the ajax-loaded images are unaffected.
Firebug, and all the other debugging tools let you profile your functions. You can see how long they take to run and how many times they have been called.
http://getfirebug.com/javascript
See: Profile JavaScript performance
Another useful tool to look into is the profile() function
console.log('Starting Profile');
console.profile();
SuspectFunction();
console.profileEnd();
Though the console window in the debugger you can see the profile results.
The best tool I have used is https://developers.google.com/web-toolkit/speedtracer/ for Chrome
To answer your first question, 15 pages of images should not be a problem for a computer to handle. Google loads up to 46 pages of images without lagging at all. Although it does stop you from loading more after that.
The answer your second question, there are many ways to track JS code. Since you are doing a performance related debugged, I'd go with timestamped console log:
console.log(" message " + new Date());
I'd put one in the beginning and end of function you are interested in measuring the performance of, and read through the log to see how long it takes to execute each of those functions. You would compare the timestamp to see what excess code is executing and how long it took for the code to execute.
Finally, in Firebug, go to the console tab, and click on Pofile before you start you start scrolling down the page. Then scroll to your 15th page, and then click Profile again. It breaks down function called and amount of time it took.
I prefer to use the timer function in Firebug or Chrome, it can be called like this:
console.time('someFunction timer');
function someFunction(){ ... }
console.timeEnd('someFunction timer');
This isn't as robust as the profiler functions, but it should give you an idea of how long functions are taking.
Also if you are running at 100% CPU and 3GB of memory, you almost certainly have a memory leak. You may want to consider removing some the initial images, when more pages are loaded in. For example, after 5 pages being shown, you remove the first page when the user views the 6th page.
I was able to fix the problem by going over my code again. I was loading new images via ajax but I had an older line of code that was checking all images, ie $('img') to replace any images that failed to load with a generic image. This means that as I continually load new images, this selector has to iterate over the entire growing dom again and again. I altered that code and now the page is flying! Thanks everyone for the help.

Categories