Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: modify delayLoad functionality #17

Merged
merged 22 commits into from Nov 29, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 3 additions & 17 deletions gatsby-browser.js
Expand Up @@ -8,10 +8,6 @@ exports.onRouteUpdate = function (_ref, _ref2) {

function trackRudderStackPage() {
if (trackPage) {
// Adding a delay (defaults to 50ms when not provided by plugin option `trackPageDelay`)
// ensure that the RudderStack route tracking is in sync with the actual Gatsby route
// (otherwise you can end up in a state where the RudderStack page tracking reports
// the previous page on route change).
var delay = Math.max(0, trackPageDelay);

window.setTimeout(function () {
Expand All @@ -20,34 +16,24 @@ exports.onRouteUpdate = function (_ref, _ref2) {
}
}

// IMPORTANT: If you are cloning the contents of this file,
// we recommend to keep this section of the code intact and
// just change the tracking logic in `trackRudderStackPage` method.
if (window.rudderSnippetLoaded === false) {
if (window.rudderSnippetLoading === true) {
// As the loading is in progress, set the alternate callback function
// to track page
window.rudderSnippetLoadedCallback = function () {
trackRudderStackPage();
};
} else {
// if it is not the first page
if (prevLocation) {
// Trigger the script loader and set the callback function
// to track page
window.rudderSnippetLoadedCallback = undefined;
window.rudderSnippetLoader(function () {
trackRudderStackPage();
});
} else {
// As this is the first page, set the alternate callback function
// to track page and wait for the scroll event to occur (for SDK to get loaded)
} else {
window.rudderSnippetLoadedCallback = function () {
trackRudderStackPage();
}
};
}
}
} else {
trackRudderStackPage();
}
};
};
156 changes: 40 additions & 116 deletions gatsby-ssr.js
Expand Up @@ -4,136 +4,60 @@ var _react = require("react");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.onRenderBody = function (_ref, pluginOptions) {
var setHeadComponents = _ref.setHeadComponents;
var trackPage = pluginOptions.trackPage,
prodKey = pluginOptions.prodKey,
devKey = pluginOptions.devKey,
_pluginOptions$dataPl = pluginOptions.dataPlaneUrl,
dataPlaneUrl =
_pluginOptions$dataPl === undefined
? "https://hosted.rudderlabs.com"
: _pluginOptions$dataPl,
controlPlaneUrl = pluginOptions.controlPlaneUrl,
delayLoad = pluginOptions.delayLoad,
delayLoadTime = pluginOptions.delayLoadTime,
manualLoad = pluginOptions.manualLoad,
loadType = pluginOptions.loadType,
useNewSDK = pluginOptions.useNewSDK,
useBetaSDK = pluginOptions.useBetaSDK,
loadOptions = pluginOptions.loadOptions,
sdkURL = pluginOptions.sdkURL;

var sdkSrc = "https://cdn.rudderlabs.com/v1/rudder-analytics.min.js";
prodKey = pluginOptions.prodKey,
devKey = pluginOptions.devKey,
_pluginOptions$dataPl = pluginOptions.dataPlaneUrl,
dataPlaneUrl = _pluginOptions$dataPl === undefined ? "https://hosted.rudderlabs.com" : _pluginOptions$dataPl,
controlPlaneUrl = pluginOptions.controlPlaneUrl,
delayLoad = pluginOptions.delayLoad,
delayLoadTime = pluginOptions.delayLoadTime,
manualLoad = pluginOptions.manualLoad,
loadType = pluginOptions.loadType,
sdkURL = pluginOptions.sdkURL,
_pluginOptions$loadOp = pluginOptions.loadOptions,
loadOptions = _pluginOptions$loadOp === undefined ? {} : _pluginOptions$loadOp;


var sdkSrc = "https://cdn.rudderlabs.com/v1.1/rudder-analytics.min.js";
if (sdkURL) sdkSrc = sdkURL;
else if (useBetaSDK) {
sdkSrc = "https://cdn.rudderlabs.com/v1.1/beta/rudder-analytics.min.js";
} else if (useNewSDK) {
sdkSrc = "https://cdn.rudderlabs.com/v1.1/rudder-analytics.min.js";
}

if (!prodKey || prodKey.length < 10)
console.error(
"Your RudderStack prodKey must be at least 10 char in length."
);
if (!prodKey || prodKey.length < 10) console.error("Your RudderStack prodKey must be at least 10 char in length.");

if (devKey && devKey.length < 10)
console.error(
"If present, your RudderStack devKey must be at least 10 char in length."
);
if (devKey && devKey.length < 10) console.error("If present, your RudderStack devKey must be at least 10 char in length.");

var writeKey = process.env.NODE_ENV === "production" ? prodKey : devKey;

var loadConfig = "'" + writeKey + "', '" + dataPlaneUrl + "'";
loadOptions.configUrl = controlPlaneUrl || loadOptions.configUrl;
MoumitaM marked this conversation as resolved.
Show resolved Hide resolved

var loadConfig = "'" + writeKey + "', '" + dataPlaneUrl + "', " + JSON.stringify(loadOptions);
MoumitaM marked this conversation as resolved.
Show resolved Hide resolved

if (loadOptions) {
// Override config URL if provided separately
loadOptions.configUrl = controlPlaneUrl || loadOptions.configUrl;
loadConfig += ", " + JSON.stringify(loadOptions);
var scriptTagStr = "var s = document.createElement(\"script\");\n s.type = \"text/javascript\";\n s.src = \"" + sdkSrc + "\";";
if (loadType === "async") {
scriptTagStr += "s.async = true;";
} else if (loadType === "defer") {
scriptTagStr += "s.defer = true;";
}
scriptTagStr += "document.head.appendChild(s);";

var snippet = "rudderanalytics=window.rudderanalytics=[];for(var methods=[\"load\",\"page\",\"track\",\"identify\",\"alias\",\"group\",\"ready\",\"reset\",\"getAnonymousId\",\"setAnonymousId\"],i=0;i<methods.length;i++){var method=methods[i];rudderanalytics[method]=function(a){return function(){rudderanalytics.push([a].concat(Array.prototype.slice.call(arguments)))}}(method)}\n " + scriptTagStr + "\n";

var snippet =
'rudderanalytics=window.rudderanalytics=[];for(var methods=["load","page","track","identify","alias","group","ready","reset","getAnonymousId","setAnonymousId"],i=0;i<methods.length;i++){var method=methods[i];rudderanalytics[method]=function(a){return function(){rudderanalytics.push([a].concat(Array.prototype.slice.call(arguments)))}}(method)}\n ' +
(delayLoad || manualLoad
? ""
: "rudderanalytics.load(" + loadConfig + ")") +
";\n";

const delayedLoader = `
window.rudderSnippetLoaded = false;
window.rudderSnippetLoading = false;
window.rudderSnippetLoadedCallback = undefined;
window.rudderSnippetLoader = function (callback) {
if (!window.rudderSnippetLoaded && !window.rudderSnippetLoading) {
window.rudderSnippetLoading = true;
function loader() {
window.rudderanalytics.load(${loadConfig});
window.rudderSnippetLoading = false;
window.rudderSnippetLoaded = true;
if (callback) { callback(); }
if (window.rudderSnippetLoadedCallback) {
window.rudderSnippetLoadedCallback();
window.rudderSnippetLoadedCallback = undefined;
}
};

"requestIdleCallback" in window
? requestIdleCallback(function () { loader(); })
: loader();
}
}
window.addEventListener('scroll',function () {window.rudderSnippetLoader()}, { once: true });
setTimeout(
function () {
"requestIdleCallback" in window
? requestIdleCallback(function () { window.rudderSnippetLoader(); })
: window.rudderSnippetLoader();
},
${delayLoadTime} || 1000
);
`;

var snippetToUse =
"\n " +
(delayLoad && !manualLoad ? delayedLoader : "") +
"\n " +
snippet +
"\n ";
var instantLoader = "" + snippet + (delayLoad || manualLoad ? "" : "rudderanalytics.load(" + loadConfig + ")") + ";";

var delayedLoader = "\n window.rudderSnippetLoaded = false;\n window.rudderSnippetLoading = false;\n window.rudderSnippetLoadedCallback = undefined;\n window.rudderSnippetLoader = function (callback) {\n if (!window.rudderSnippetLoaded && !window.rudderSnippetLoading) {\n window.rudderSnippetLoading = true;\n function loader() {\n " + snippet + "\n window.rudderanalytics.load(" + loadConfig + ");\n window.rudderSnippetLoading = false;\n window.rudderSnippetLoaded = true;\n if (callback) { callback(); }\n if (window.rudderSnippetLoadedCallback) {\n window.rudderSnippetLoadedCallback();\n window.rudderSnippetLoadedCallback = undefined;\n }\n };\n\n \"requestIdleCallback\" in window\n ? requestIdleCallback(function () { loader(); })\n : loader();\n }\n }\n window.addEventListener('scroll',function () {window.rudderSnippetLoader()}, { once: true });\n setTimeout(\n function () {\n \"requestIdleCallback\" in window\n ? requestIdleCallback(function () { window.rudderSnippetLoader(); })\n : window.rudderSnippetLoader();\n },\n " + delayLoadTime + " || 1000\n );\n ";

var snippetToUse = "" + (delayLoad && !manualLoad ? delayedLoader : instantLoader);

if (writeKey) {
var tags = [
_react2.default.createElement("script", {
key: "plugin-rudderstack",
dangerouslySetInnerHTML: { __html: snippetToUse },
}),
];

var tag = void 0;

if (loadType == "async") {
tag = _react2.default.createElement("script", {
async: true,
key: "rudderstack-cdn",
src: sdkSrc,
});
} else if (loadType == "defer") {
tag = _react2.default.createElement("script", {
defer: true,
key: "rudderstack-cdn",
src: sdkSrc,
});
} else {
tag = _react2.default.createElement("script", {
key: "rudderstack-cdn",
src: sdkSrc,
});
}

tags.push(tag);
var tags = [_react2.default.createElement("script", {
key: "plugin-rudderstack",
dangerouslySetInnerHTML: { __html: snippetToUse }
})];

setHeadComponents(tags);
}
};
};
55 changes: 21 additions & 34 deletions src/gatsby-ssr.js
Expand Up @@ -11,18 +11,12 @@ exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
delayLoadTime,
manualLoad,
loadType,
useNewSDK,
sdkURL,
useBetaSDK,
loadOptions = {},
} = pluginOptions;

var sdkSrc = "https://cdn.rudderlabs.com/v1/rudder-analytics.min.js";
var sdkSrc = "https://cdn.rudderlabs.com/v1.1/rudder-analytics.min.js";
if (sdkURL) sdkSrc = sdkURL;
else if (useBetaSDK) {
sdkSrc = "https://cdn.rudderlabs.com/v1.1/beta/rudder-analytics.min.js";
} else if (useNewSDK) {
sdkSrc = "https://cdn.rudderlabs.com/v1.1/rudder-analytics.min.js";
}

// ensures RudderStack production write key is present
if (!prodKey || prodKey.length < 10)
Expand All @@ -40,21 +34,27 @@ exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
// note below, snippet wont render unless writeKey is truthy
const writeKey = process.env.NODE_ENV === "production" ? prodKey : devKey;

const loadConfig = controlPlaneUrl
? `'${writeKey}', '${dataPlaneUrl}', {configUrl: '${controlPlaneUrl}'}`
: `'${writeKey}', '${dataPlaneUrl}'`;
/*
if (controlPlaneUrl) {
return `'${writeKey}', '${dataPlaneUrl}', {configUrl: '${controlPlaneUrl}'}`;
} else {
return `'${writeKey}', '${dataPlaneUrl}'`;
}
}; */
// Override config URL if provided separately
loadOptions.configUrl = controlPlaneUrl || loadOptions.configUrl;

const loadConfig = `'${writeKey}', '${dataPlaneUrl}', ${JSON.stringify(loadOptions)}`;

let scriptTagStr = `var s = document.createElement("script");
s.type = "text/javascript";
s.src = "${sdkSrc}";`;
if (loadType === "async") {
scriptTagStr += "s.async = true;";
} else if (loadType === "defer") {
scriptTagStr += "s.defer = true;";
}
scriptTagStr += "document.head.appendChild(s);";

const snippet = `rudderanalytics=window.rudderanalytics=[];for(var methods=["load","page","track","identify","alias","group","ready","reset","getAnonymousId","setAnonymousId"],i=0;i<methods.length;i++){var method=methods[i];rudderanalytics[method]=function(a){return function(){rudderanalytics.push([a].concat(Array.prototype.slice.call(arguments)))}}(method)}
${delayLoad || manualLoad ? `` : `rudderanalytics.load(${loadConfig})`};
${scriptTagStr}
`;

const instantLoader = `${snippet}${delayLoad || manualLoad ? `` : `rudderanalytics.load(${loadConfig})`};`;

const delayedLoader = `
window.rudderSnippetLoaded = false;
window.rudderSnippetLoading = false;
Expand All @@ -63,6 +63,7 @@ exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
if (!window.rudderSnippetLoaded && !window.rudderSnippetLoading) {
window.rudderSnippetLoading = true;
function loader() {
${snippet}
window.rudderanalytics.load(${loadConfig});
window.rudderSnippetLoading = false;
window.rudderSnippetLoaded = true;
Expand Down Expand Up @@ -90,10 +91,7 @@ exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
`;

// if `delayLoad` option is true, use the delayed loader
const snippetToUse = `
${delayLoad && !manualLoad ? delayedLoader : ""}
${snippet}
`;
const snippetToUse = `${delayLoad && !manualLoad ? delayedLoader : instantLoader}`;

// only render snippet if write key exists
if (writeKey) {
Expand All @@ -104,17 +102,6 @@ exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
/>,
];

let tag;

if (loadType == "async") {
tag = <script async key="rudderstack-cdn" src={sdkSrc}></script>;
} else if (loadType == "defer") {
tag = <script defer key="rudderstack-cdn" src={sdkSrc}></script>;
} else {
tag = <script key="rudderstack-cdn" src={sdkSrc}></script>;
}

tags.push(tag);
setHeadComponents(tags);
}
};