Javascript loading issues


(Rdiepenbrock) #1

Hi all.
Here is my current build: https://rjd.docs.stoplight.io/user-manual

I am having issues with loading the various scripts I need on the page. I am using the javascript field under Publish -> Advanced. I am also adding script blocks to my HTML page. The scripts are needed for the Code sample preference bar, which shows/hides code snippets further down the page.
I have been testing different methods and arrangements so the scripts load and execute correctly.

Would appreciate any insight and suggestions.


(Taylor Barnett) #2

Hey @rdiepenbrock!

Interesting use case - I like it! It looks like the JS code is being loaded into the head tag properly, so it probably has something to do with the code itself or how it is executing.

I’ll need to pull in one of our frontend engineers to take a look. I’ll let you know what I find out.


(Taylor Barnett) #3

I think it would help to understand what should happen when I click “Ruby” for example.


(Taylor Barnett) #4

One more question: Where did you hook up the click events?


(Rdiepenbrock) #5

I got it to sort of work by removing the code that was throwing the exception. However, it only works after a page reload.

This is the main page, and generally, the first page a visitor will see. They can click one of the coding languages in the preference bar, which sets a cookie. When the visitor browses subsequent pages, such as the User Manual, there are code examples on the page - only the code for the selected language will be displayed.

How can I execute this JavaScript when the page initially loads? Whether the user directly hits the page, or comes in from the navigation sidebar?


(Taylor Barnett) #6

Here’s a script that might help:

    var pushState = history.pushState;
    history.pushState = function(state) {
        if (typeof history.onpushstate == "function") {
            history.onpushstate({state: state});
        }
		
        // ... whatever else you want to do

        return pushState.apply(history, arguments);
    };
})(window.history);

It will hook into the history change event (navigating pages).


(Rdiepenbrock) #7

Is there an opening line to the script, which is closed by (window.history)?


(Taylor Barnett) #8

Yup! Sorry about that. Forgot to copy it over:

Here’s it complete:

(function(history){
    var pushState = history.pushState;
    history.pushState = function(state) {
        if (typeof history.onpushstate == "function") {
            history.onpushstate({state: state});
        }
		
        // ... whatever else you want to do

        return pushState.apply(history, arguments);
    };
})(window.history);

(Rdiepenbrock) #9

This appears to work on a few pages:

But not on the rest of the pages. An example: https://rjd.docs.stoplight.io/quickstart/tracking-events
No errors in dev tools.