JS -исполнение медленнее в бинарном хромах по сравнению с загруженным бинарным хромами.Javascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 JS -исполнение медленнее в бинарном хромах по сравнению с загруженным бинарным хромами.

Сообщение Anonymous »

Я использую кукол для запуска кучу JS для обработки HTML -файлов в безголовом хроме. Я заметил, что когда я использую бинарный хромий, загруженный с https://storage.googleapis.com/chromium ... 4/1148123/, JS завершается ~ 300 мс. Но когда я загружаю и строю тег 115.0.5790.102 с флагами Disable_fieldtrial_testing_config = true и is_debug = false , он работает за ~ 840 мс. Бинарный размер хрома также увеличивается на ~ 70 МБ. Мне не хватает флагов? Хотелось бы некоторые указатели о том, почему выполнение может быть медленнее в застроенное двоичное. Сценарий для запуска хрома и времени обработки печати: < /p>
const puppeteer = require('puppeteer');
const path = require('path');
const fs = require('fs');
const os = require('os');

/**
* Test script to run the computedStyleInliner script in Chromium using Puppeteer
* This script loads the fiction story HTML file and executes the style inliner,
* then captures the results for analysis.
*/
const Platform = {
DARWIN: "darwin",
MAC: "mac",
LINUX: "linux",
WIN32: "win32",
WIN64: "win64",
};

function getPlatform() {
const ARCH_X64 = 'x64';
const platform = os.platform();
if (platform === Platform.DARWIN)
return Platform.MAC;
else if (platform === Platform.LINUX)
return Platform.LINUX;
else if (platform === Platform.WIN32)
return (os.arch() === ARCH_X64 ? Platform.WIN64 : Platform.WIN32);
else
throw new Error('Unsupported platform: ' + platform);
}

function getChromiumExecutablePath() {
const folderPath = process.env.CHROMIUM_PATH;
const platform = getPlatform();
let executablePath = '';
if (platform === Platform.MAC)
executablePath = path.join(folderPath, 'Chromium.app', 'Contents', 'MacOS', 'Chromium');
else if (platform === Platform.LINUX) {
executablePath = path.join(folderPath, 'chrome-wrapper');
} else if (platform === Platform.WIN32 || platform === Platform.WIN64)
executablePath = path.join(folderPath, 'chrome.exe');
else
throw new Error('Unsupported platform: ' + platform);

return executablePath;
}

async function testComputedStyleInliner() {
console.log('Starting Computed Style Inliner test...');

let browser;
try {
// Launch Chromium browser
browser = await puppeteer.launch({
executablePath: getChromiumExecutablePath(),
headless: process.env.HEADLESS === 'true', // Set to true for headless mode
devtools: false,
protocolTimeout: 0,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--disable-gpu',
'--auto-open-devtools-for-tabs'
]
});

const page = await browser.newPage();

// Set viewport size
await page.setViewport({ width: 1200, height: 800 });

// Get the absolute path to the fiction story HTML file
const htmlFilePath = path.resolve(__dirname, 'fiction-story.html');
const fileUrl = `file://${htmlFilePath}`;

console.log(`Loading HTML file: ${fileUrl}`);

// Check if the HTML file exists
if (!fs.existsSync(htmlFilePath)) {
throw new Error(`HTML file not found: ${htmlFilePath}`);
}

// Navigate to the HTML file
await page.goto(fileUrl, { waitUntil: 'networkidle0' });

console.log('Page loaded successfully');

// Wait a moment for any initial rendering
await page.waitForTimeout(1000);

// Count elements before style inlining
const elementCountBefore = await page.evaluate(() => {
return document.querySelectorAll('*').length;
});

console.log(`Total elements found: ${elementCountBefore}`);

// Check if the computedStyleInliner script is loaded
const scriptLoaded = await page.evaluate(() => {
return typeof inlineComputedStyles !== 'undefined';
});
let time = 0;
if (!scriptLoaded) {
console.log('ComputedStyleInliner script not found as global function, executing inline...');

// Read and execute the computedStyleInliner script
const scriptPath = path.resolve(__dirname, 'computedStyleInliner.js');

if (!fs.existsSync(scriptPath)) {
throw new Error(`ComputedStyleInliner script not found: ${scriptPath}`);
}

const scriptContent = fs.readFileSync(scriptPath, 'utf8');

time = await page.evaluate(scriptContent);
console.log('ComputedStyleInliner script executed with time:' + time);
} else {
console.log('ComputedStyleInliner script already loaded');
}

// Wait a moment for any final processing
await page.waitForTimeout(500);

// Count elements with inline styles after processing
const elementsWithInlineStyles = await page.evaluate(() => {
const elements = document.querySelectorAll('*');
let count = 0;
elements.forEach(el => {
if (el.getAttribute('style') && el.getAttribute('style').trim() !== '') {
count++;
}
});
return count;
});

console.log(`Elements with inline styles after processing: ${elementsWithInlineStyles}`);

// Get sample of inlined styles for verification
const sampleStyles = await page.evaluate(() => {
const elements = document.querySelectorAll('*');
const samples = [];
let count = 0;

for (let el of elements) {
const style = el.getAttribute('style');
if (style && style.trim() !== '' && count < 10) {
samples.push({
tagName: el.tagName,
className: el.className,
style: style.substring(0, 200) + (style.length > 200 ? '...' : '')
});
count++;
}
}
return samples;
});

// Capture console messages
const consoleMessages = [];
page.on('console', msg => {
console.log(msg);
consoleMessages.push({
type: msg.type(),
text: msg.text()
});
});

// Get the final HTML with inlined styles
const finalHtml = await page.content();

// Save the result to a file for inspection
const outputPath = path.resolve(__dirname, 'output/fiction-story-with-inlined-styles.html');

// Ensure output directory exists
const outputDir = path.dirname(outputPath);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}

fs.writeFileSync(outputPath, finalHtml, 'utf8');
console.log(`\nResult saved to: ${outputPath}`);

return {
success: true,
outputPath: outputPath,
};

} catch (error) {
console.error('Error during test execution:', error);
return {
success: false,
error: error.message
};
} finally {
if (browser) {
await browser.close();
console.log('\nBrowser closed');
}
}
}

// Run the test if this script is executed directly
if (require.main === module) {
testComputedStyleInliner()
.then(result => {
if (result.success) {
console.log('\n✅ Test completed successfully!');
process.exit(0);
} else {
console.log('\n❌ Test failed:', result.error);
process.exit(1);
}
})
.catch(error => {
console.error('\n💥 Unexpected error:', error);
process.exit(1);
});
}

module.exports = { testComputedStyleInliner };



Подробнее здесь: https://stackoverflow.com/questions/797 ... romium-bin
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Исполнение JS в хроме медленнее, чем Phantomjs
    Anonymous » » в форуме Javascript
    0 Ответы
    9 Просмотры
    Последнее сообщение Anonymous
  • В чем разница между reg: логистическим и бинарным: логистикой в ​​XGBoost
    Anonymous » » в форуме Python
    0 Ответы
    17 Просмотры
    Последнее сообщение Anonymous
  • PHP: Определите, является ли строка либо текстом, либо бинарным, на строках без байтов NUL
    Anonymous » » в форуме Php
    0 Ответы
    15 Просмотры
    Последнее сообщение Anonymous
  • PHP: Определите, является ли строка либо текстом, либо бинарным, на строках без байтов NUL
    Anonymous » » в форуме Php
    0 Ответы
    11 Просмотры
    Последнее сообщение Anonymous
  • Мауи сетевой копия файла с бинарным Android
    Anonymous » » в форуме Android
    0 Ответы
    4 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Javascript»